I am trying to select all BUT certain index pairs in a multi-dimensional array. i.e. I have a set of paired indices (e.g. [1,2] and [4,5]). I want to set all BUT those indexed pairs to 0.
The closest I have come to this is:
A(setdiff(1:length(A(:,1)),lon),setdiff(1:length(A(1,:)),lat)) = 0;
, where A is the matrix and lon and lat are the index pairs I want to keep. However, that also leaves all the intersecting rows and columns of those pairs.
Any ideas?
Here is some example code:
A = ones([5,5])
A =
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
lon = [1];
lat = [4];
A(setdiff(1:length(A(:,1)),lon),setdiff(1:length(A(1,:)),lat)) = 0
A =
1 1 1 1 1
0 0 0 1 0
0 0 0 1 0
0 0 0 1 0
0 0 0 1 0
What I want is:
A =
0 0 0 1 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
The easiest thing to do is actually the opposite of what you have tried. First you want to start with a matrix of zeros and then only fill in those pairs that you have stored in lat and lon. Also because you have paired subscripts, you will want to convert those to a linear index using sub2ind
%// Convert subscripts to a linear index
inds = sub2ind(size(A), lon, lat);
%// Start off with a matrix of zeros
B = zeros(size(A));
%// Fill in the values at the specified lat/lon from A
B(inds) = A(inds);
Related
I'm working in Matlab and I have the following problem:
I have a 2x4 matrix A
A = 0 0 0 0
0 0 0 0
and index matrix
index = 1 2
2 3
each row of index matrix indicates the location I want to assign in A. What should I do to make A be
A = 1 1 0 0
0 1 1 0
Another Example: if index is
index = 1 3
2 4
then
A = 1 0 1 0
0 1 0 1
Thanks!
You can do this using linear indexing and implicit expansion:
A((index-1).*size(A,1)+(1:size(index,1)).') = 1;
Say I have a vector A of item IDs:
A=[50936
332680
107430
167940
185820
99732
198490
201250
27626
69375];
And I have a matrix B whose rows contains values of 8 parameters for each of the items in vector A:
B=[0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
1 0 1 0 0 1 0 1 1 1
1 0 1 0 0 1 0 1 1 1
0 0 1 0 0 0 0 1 0 1
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1];
So, column 1 in matrix B represents data of item in row 1 of vector A, column 2 in matrix B represents data of item in row 2 of vector A, and so on. However, I want matrix B to contain the information in a different order of items stored in vector A2:
A2=[185820
198490
69375
167940
99732
332680
27626
107430
50936
201250];
How do I sort them, so that column 1 of matrix B contains data for item in row 1 of vector A2, column 2 of matrix B contains data for item in row 2 of vector A2, and so on?
My extremely crude solution to do this is the following:
A=A'; A2=A2';
for i=1:size(A,2)
A(2:size(B,1)+1,i)=B(:,i);
end
A2(2:size(B,1)+1,:)=zeros(size(B,1),size(B,2));
for i=size(A2,2)
for j=size(A,2)
if A2(1,i)==A(1,j)
A2(2:end,i)=A(2:end,j);
end
end
end
B2 = A2(2:end,:);
But I would like to know a cleaner, more elegant and less time consuming method to do this.
A possible solution
You can use second output of ismember function.
[~ ,idx] = ismember(A2,A);
B2 = B(:,idx);
Update:I tested both my solution and another proposed by hbaderts
disp('-----ISMEMBER:-------')
tic
[~,idx]=ismember(A2,A);
toc
disp('-----SORT:-----------')
tic
[~,idx1] = sort(A);
[~,idx2] = sort(A2);
map = zeros(1,size(idx2));
map(idx2) = idx1;
toc
Here is the result in Octave:
-----ISMEMBER:-------
Elapsed time is 0.00157714 seconds.
-----SORT:-----------
Elapsed time is 4.41074e-05 seconds.
Conclusion: the sort method is more efficient!
As both A and A2 contain the exact same elements, just sorted differently, we can create a mapping from the A-sorting to the A2-sorting. For that, we run the sort function on both and save indexes (which are the second output).
[~,idx1] = sort(A);
[~,idx2] = sort(A2);
Now, the first element in idx1 corresponds to the first element in idx2, so A(idx1(1)) is the same as A2(idx2(1)) (which is 27626). To create a mapping idx1 -> idx2, we use matrix indexing as follows
map = zeros(size(idx2));
map(idx2) = idx1;
To sort B accordingly, all we need to do is
B2 = B(:, map);
[A2, sort_order] = sort(A);
B2 = B(:, sort_order)
MATLAB's sort function returns the order in which the items in A are sorted. You can use this to order the columns in B.
Transpose B so you can concatenate it with A:
C = [A B']
Now you have
C = [ 50936 0 0 1 1 0 0 0 0;
332680 0 0 0 0 0 0 0 0;
107430 0 0 1 1 1 0 0 0;
167940 0 0 0 0 0 0 0 0;
185820 0 0 0 0 0 0 0 0;
99732 0 0 1 1 0 0 0 0;
198490 0 0 0 0 0 0 0 0;
201250 0 0 1 1 1 1 0 0;
27626 0 0 1 1 0 0 0 0;
69375 0 0 1 1 1 0 0 1];
You can now sort the rows of the matrix however you want. For example, to sort by ID in ascending order, use sortrows:
C = sortrows(C)
To just swap rows around, use a permutation of 1:length(A):
C = C(perm, :)
where perm could be something like [4 5 6 3 2 1 8 7 9 10].
This way, your information is all contained in one structure and the data is always correctly matched to the proper ID.
I'd like to create a Matrix in MATLAB where:
The First row consists of a random arrangement of 0s and 1s, split evenly (i.e. 50-50).
The Second row randomly assigns zeros to 50% of the 0s and 1s in the first row, and ones to the remaining 50%.
The Third row randomly assigns zeros to 50% of the 0s and 1s in the second row, and ones to the remaining 50%.
Non-randomized Example:
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
Any suggestions?
A solution based on checking whether numbers are bigger or smaller than the median. As long as the number of columns tested is even, exactly half of a set of random doubles will be bigger than the median, and half will be smaller. This guarantees that there's exactly 50% of bits get flipped.
nRows = 3;
nCols = 16; %# divisible by 4
%# seed the array
%# assume that the numbers in each row are unique (very, very likely)
array = rand(nRows,nCols);
out = false(nRows,nCols);
%# first row is special
out(1,:) = array(1,:) > median(array(1,:));
%# for the rest of the row, check median for the zeros/ones in the previous row
for iRow = 2:nRows
zeroIdx = out(iRow-1,:) == 0;
%# > or < do not matter, both will replace zeros/ones
%# and replace with exactly half zeros and half ones
out(iRow,zeroIdx) = array(iRow,zeroIdx) > median(array(iRow,zeroIdx));
out(iRow,~zeroIdx) = array(iRow,~zeroIdx) > median(array(iRow,~zeroIdx));
end
I'd offer a short bsxfun solution:
%// number of divisions
n = 4;
%// unshuffled matrix like in your example
unshuffled = bsxfun(#(a,b) mod(a,2*b) > b-1, meshgrid(1:n^2,1:n) - 1, (2.^((n-1):-1:0)).') %'
%// shuffle columns
shuffled = unshuffled(:,randperm(n^2))
unshuffled =
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
shuffled =
1 0 1 1 0 1 0 1 1 1 1 0 0 0 0 0
1 1 1 0 0 1 1 0 1 0 0 0 1 0 1 0
1 0 0 1 0 0 0 0 1 1 0 1 1 0 1 1
1 1 1 1 0 0 0 0 0 0 1 0 0 1 1 1
First you need to create the unshuffled matrix, which can be done by comparing the matrix generated by meshgrid(1:n^2,1:n) with a row dependent modulus. Finally you just need to shuffle the columns.
If you have the Statistics Toolbox, you can do it very easily with randsample:
M = 3; %// number of rows
N = 16; %// number of columns. Should be multiple of 4, according to problem definition
result = zeros(M,N); %// preallocate and initiallize to zeros
result(1, randsample(1:N,N/2)) = 1; %// first row: half values set to one, half to zero
for m = 2:M
result(m, :) = result(m-1, :); %// initiallize row m equal to row m-1
result(m, randsample(find(result(m-1,:)), N/4)) = 0; %// change half of ones
result(m, randsample(find(~result(m-1,:)), N/4)) = 1; %// change half of zeros
end
Example result:
result =
0 1 0 1 1 0 0 0 0 1 0 1 1 0 1 1
1 1 0 0 0 1 1 1 0 1 0 1 0 0 0 1
1 0 0 0 1 0 0 1 0 1 1 0 1 1 0 1
A solution using randperm:
nrows = 3;
ncols = 16;
M = zeros(nrows,ncols);
%// seed the first row
M(1,1:ncols/2) = 1;
M(1,:) = M(1,randperm(ncols));
for r = 2:nrows
%// Find ncols/4 random between 1 and ncols/2. These will be used to index half of the previous rows 1 elements and set them to one
idx = randperm(ncols/2);
idx1 = idx(1:ncols/4);
%// Do the same thing again, but this time it will be used for the 0 elements of the previous row
idx = randperm(ncols/2);
idx0 = idx(1:ncols/4);
idx_prev1 = find(M(r-1,:)); %// Find where the 1 elements were in the last row
idx_prev0 = find(~M(r-1,:)); %// Find where the 0 elements were in the last row
M(r,idx_prev1(idx1))=1; %// Set half of the previous rows 1 elements in this row to 1
M(r,idx_prev0(idx0))=1; %// Set half of the previous rows 0 elements in this row to 1
end
Per my previous question couple days ago, now, I have several mx3 matrices with rows from (0,1,num), (-1,0,num), (0,1,num), (0,-1,num), (1,1,num), (-1,1,num), (1,-1,num),(-1,-1,num), where num is an integer which can take any values between 0 to 3.
I would like to create a new matrix, with 8 rows, and 6 columns, where the the first two columns represent each of the above coordinates, and each of the remaining columns indicate the frequency
of each of the above coordinates at each num values. i.e. columns 3 of each row indicates the number of times we see the coordinate corresponding to that row with and num=0. columns 4 of each row indicates the number of times we see the coordinate corresponding to that row with and num=1.
columns 5 of each row indicates the number of times we see the coordinate corresponding to that row with and num=2, and columns 6 of each row indicates the number of times we see the coordinate corresponding to that row with and num=3.
For instance, if A=[0 1 1
1 1 1
1 1 0
1 0 0
1 1 0
1 1 0
1 1 0
1 1 0
1 1 0
1 -1 0
1 1 0
1 1 3
1 1 2
1 1 3
1 1 3]
I would like to see something like:
-1 -1 0 0 0 0
-1 0 0 0 0 0
-1 1 0 0 0 0
0 -1 0 0 0 0
0 1 0 1 0 0
1 -1 1 0 0 0
1 0 1 0 0 0
1 1 7 1 1 3
Is there a way to do it? Thanks.
Try this:
counts = zeros(9, 6); % Initialize output matrix
k = 1;
for ii = -1:1
for jj = -1:1
ijCoords = (A(:,1) == ii) & (A(:,2) == jj); % Find rows containing coordinate (ii,jj)
ijCount = histc(A(ijCoords,3), 0:3); % Count how many 0,1,2,3 in these rows
counts(k,:) = [ii, jj, ijCount(:)']; % Add the counts to the next row of the output matrix
k = k + 1;
end
end
counts(5, :) = []; % Remove coordinate (0,0) because you don't want it.
I am having some problems with the find function in MATLAB. I have a matrix consisting of zeros and ones (representing the geometry of a structural element), where material is present when the matrix element = 1, and where no material is present when the matrix element = 0. The matrix may have the general form shown below (it will update as the geometry is changed, but that isn't too important).
Geometry = [0 0 0 0 0 0 0 0 0 0;
0 0 1 0 1 0 1 1 0 0;
0 0 1 0 0 0 0 1 0 0;
0 0 1 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 1 0 0;
0 0 0 0 0 0 0 0 0 0;
0 0 1 0 0 0 0 1 0 0;
0 0 1 0 0 0 0 1 0 0;
0 0 1 1 1 1 0 1 0 0;
0 0 0 0 0 0 0 0 0 0;]
I'm trying to find the the rows and columns that are not continuously connected (i.e. where the row and columns are not all equal to 1 between the outer extents of the row or column) and then update them so they are all connected. I.e. the matrix above becomes:
Geometry = [0 0 0 0 0 0 0 0 0 0;
0 0 1 1 1 1 1 1 0 0;
0 0 1 0 0 0 0 1 0 0;
0 0 1 0 0 0 0 1 0 0;
0 0 1 0 0 0 0 1 0 0;
0 0 1 0 0 0 0 1 0 0;
0 0 1 0 0 0 0 1 0 0;
0 0 1 0 0 0 0 1 0 0;
0 0 1 1 1 1 1 1 0 0;
0 0 0 0 0 0 0 0 0 0;]
The problem I am having is I want to be able to find the indices of the first and last element that is equal to 1 in each row (and column), which will then be used to update the geoemtry matrix.
Ideally, I want to represent these in vectors, so going across the columns, find the row number of the first element equal to 1 and store this in a vector called rowfirst.
I.e.:
rowfirst = zeros(1,numcols)
for i = 1:numcols % Going across the columns
rowfirst(i) = find(Geometry(i,1) == 1, 1,'first')
% Store values in vector called rowfirst
end
and the repeat this for the columns and to find the last elements in each row.
For some reason, I can't get the values to store properly in the vector, does anyone have an idea of where I'm going wrong?
Thanks in advance. Please let me know if that isn't clear, as I may not have explained the problem very well.
0) bwmorph(Geometry,'close') dose it all in one line. If the holes may be bigger, try bwmorph(Geometry,'close',Inf).
Regarding your attempt:
1) It should be Geometry(i,:) instead of Geometry(i,1).
2) Your real problem here is empty matrices. Actually, what do you want rowfirst(i) to be if there are no 1s in the i'th row?
Ok, I can spot two mistakes:
You should use an array as the first argument of find. So, if you want to find the row number of the first element of each column, then you should use find(Geometry(:, i), 1, 'first').
Find returns an empty array if the column contains only zeros. You should handle this case and decide what number you want to put into rownumber (e.g. you can put -1, to indicate that the corresponding column contains no non-zero elements).
Following the above, you can try this:
for i = 1:numcols
tmp = find(Geometry(:, i), 1, 'first');
if(tmp)
rowfirst(i) = tmp;
else
rowfirst(i) = -1;
end;
end;
I'm pretty sure there's a more efficient way of doing this, but if you replace your call to find with this, it should work ok:
find(Geometry(i,:), 1,'first')
(otherwise you're just looking at the first cell of the ith row. And the == 1 is useless, since find already returns only non-zero elements, and your matrix is binary)
Use the AccumArray() function to find the min and max col (row) number.
Imagine finding the last (first) row in each column that contains a NaN.
a = [1 nan nan nan ;
2 2 3 4;
3 nan 3 3;
4 nan 4 4]
This code gets the row indices for the last NaN in each column.
[row,col] = find(isnan(a))
accumarray(col,row,[],#max)
This code gets the row indices for the first NaN in each column.
[row,col] = find(isnan(a))
accumarray(col,row,[],#min)
Swap the row and col variables to scan row-wise instead of column-wise.
This answer inspired by Finding value and index of min value in a matrix, grouped by column values