How can I use values within a MATLAB matrix as indices to determine the location of data in a new matrix? - matlab

I have a matrix that looks like the following.
I want to take the column 3 values and put them in another matrix, according to the following rule.
The value in the Column 5 is the row index for the new matrix, and Column 6 is the column index. Therefore 20 (taken from 29,3) should be in Row 1 Column 57 of the new matrix, 30 (from 30,3) should in Row 1 column 4 of the new matrix, and so on.
If the value in column 3 is NaN then I want NaN to be copied over to the new matrix.

Example:
% matrix of values and row/column subscripts
A = [
20 1 57
30 1 4
25 1 16
nan 1 26
nan 1 28
25 1 36
nan 1 53
50 1 56
nan 2 1
nan 2 2
nan 2 3
80 2 5
];
% fill new matrix
B = zeros(5,60);
idx = sub2ind(size(B), A(:,2), A(:,3));
B(idx) = A(:,1);
There are a couple other ways to do this, but I think the above code is easy to understand. It is using linear indexing.
Assuming you don't have duplicate subscripts, you could also use:
B = full(sparse(A(:,2), A(:,3), A(:,1), m, n));
(where m and n are the output matrix size)
Another one:
B = accumarray(A(:,[2 3]), A(:,1), [m,n]);

I am not sure if I understood your question clearly but this might help:
(Assuming your main matrix is A)
nRows = max(A(:,5));
nColumns = max(A(:,6));
FinalMatrix = zeros(nRows,nColumns);
for i=1:size(A,1)
FinalMatrix(A(i,5),A(i,6))=A(i,3);
end
Note that above code sets the rest of the elements equal to zero.

Related

How to distinguish the two picture matrices?

I have a picture matrix A, the size of which is 200*3000 double. And I have another picture matrix B, the size of which is 200*1000 double. The 1000 columns of matrix B exactly comes from the columns of matrix A. My question is:
How to get a matrix C with the same size of matrix A, but only keep the original values of columns in matrix B? I mean the size of matrix C is 200*3000 double, but only 1000 columns have the same values as matrix B. The other 2000 columns will be set to another value d, that is my second question, what is the value I should set for d, so that the picture matrix C can distinguish from picture matrix A?
Use ismember with the 'rows' option. Here's an example:
A = [1 2 3 4; 5 6 7 8]; %// example A
B = [3 10 1; 7 20 5]; %// example B
val = NaN; %// example value to indicate no match
C = A; %// initiallize
ind = ismember(A.',B.','rows'); %// matching columns
C(:,~ind) = val; %// set non-matching columns to val
Equivalently, you coud replace ismember by bsxfun, so that line becomes
ind = any(all(bsxfun(#eq, A, permute(B, [1 3 2])), 1), 3);
In this example,
A =
1 2 3 4
5 6 7 8
B =
3 10 1
7 20 5
C =
1 NaN 3 NaN
5 NaN 7 NaN

Reshape a matrix in matlab with nan elements

I have a Nx3-matrix in matlab, where I have a degree value from 0 to 360 in the first column, a radius value from 0 to 0.5 in the second and an integer in the third. Every combination out of (M(n,1),M(n,2)) is unique with M the matrix and n a random number between 1 and N, but it is possible that there is a value in M(:,1) or M(:,2) more than once. M is sorted, first after the first row, then after the second.
My target is now to reshape this matrix into a 360xV-matrix, with V the amount of unique values in M(:,2). If there is a value in M(:,3) at the position M(o,1) and M(p,2) with 1 <= o, p <= N, it should be placed at the position (o,p), if there is no value, then there should a NaN-value placed instead.
Is there a simple way to do this, or do I have to write my own function for that?
Edit:
Desired input:
0 0.25 1
0 0.43 4
1 0.25 2
2 0.03 5
2 0.43 2
Desired output:
NaN 1 4
NaN 2 NaN
5 NaN 2
You can use an approach of finding unique indices for the first and second columns from the input arrays and then using those to set elements in an appropriately (discussed in more detail inside the code as comments) sized output array with the elements from the third column. Here's the implementation -
%// Input array
A = [
0 0.25 1
0 0.43 4
1 0.25 2
2 0.03 5
2 0.43 2 ]
%// Find unique indices for col-1,2
[~,~,idx1] = unique(A(:,1)) %// these would form the row indices of output
[~,~,idx2] = unique(A(:,2)) %// these would form the col indices of output
%// Decide the size of output array based on the "extents" of those indices
nrows = max(idx1)
ncols = max(idx2)
%// Initialize output array with NaNs
out = NaN(nrows,ncols)
%// Set the elements in output indexed by those indices to values from
%// col-3 of input array
out((idx2-1)*nrows + idx1) = A(:,3)
Code run -
out =
NaN 1 4
NaN 2 NaN
5 NaN 2
Is there a simple way to do this, or do I have to write my own function for that?
You'll need to write a method, seeing that what you've described is utterly specific to your problem. There's methods to find unique values, so this will help you when designing your for loop.

how to select a submatrix from a matrix in Matlab [duplicate]

How to select a submatrix (not in any pattern) in Matlab? For example, for a matrix of size 10 by 10, how to select the submatrix consisting of intersection of the 1st 2nd and 9th rows and the 4th and 6th columns?
Thanks for any helpful answers!
TLDR: Short Answer
As for your question, suppose you have an arbitrary 10-by-10 matrix A. The simplest way to extract the desired sub-matrix would be with an index vector:
B = A([1 2 9], [4 6]);
Indexing in MATLAB
There's an interesting article in the official documentation that comprehensively explains indexing in MATLAB.
Basically, there are several ways to extract a subset of values, I'll summarize them for you:
1. Indexing Vectors
Indexing vectors indicate the indices of the element to be extracted. They can either contain a single index or several, like so:
A = [10 20 30 40 50 60 70 80 90]
%# Extracts the third and the ninth element
B = A([3 9]) %# B = [30 90]
Indexing vectors can be specified for each dimension separately, for instance:
A = [10 20 30; 40 50 60; 70 80 90];
%# Extract the first and third rows, and the first and second columns
B = A([1 3], [1 2]) %# B = [10 30; 40 60]
There are also two special subscripts: end and the colon (:):
end simply indicates the last index in that dimension.
The colon is just a short-hand notation for "1:end".
For example, instead of writing A([1 2 3], [2 3]), you can write A(:, 2:end). This is especially useful for large matrices.
2. Linear Indexing
Linear indexing treats any matrix as if it were a column vector by concatenating the columns into one column vector and assigning indices to the elements respectively. For instance, we have:
A = [10 20 30; 40 50 60; 70 80 90];
and we want to compute b = A(2). The equivalent column vector is:
A = [10;
40;
70;
20;
50;
80;
30;
60;
90]
and thus b equals 40.
The special colon and end subscripts are also allowed, of course. For that reason, A(:) converts any matrix A into a column vector.
Linear indexing with matrix subscripts:
It is also possible to use another matrix for linear indexing. The subscript matrix is simply converted into a column vector, and used for linear indexing. The resulting matrix is, however always of the same dimensions as the subscript matrix.
For instance, if I = [1 3; 1 2], then A(I) is the same as writing reshape(A(I(:)), size(I)).
Converting from matrix subscripts to linear indices and vice versa:
For that you have sub2ind and ind2sub, respectively. For example, if you want to convert the subscripts [1, 3] in matrix A (corresponding to element 30) into a linear index, you can write sub2ind(size(A), 1, 3) (the result in this case should be 7, of course).
3. Logical Indexing
In logical indexing the subscripts are binary, where a logical 1 indicates that the corresponding element is selected, and 0 means it is not. The subscript vector must be either of the same dimensions as the original matrix or a vector with the same number of elements. For instance, if we have:
A = [10 20 30; 40 50 60; 70 80 90];
and we want to extract A([1 3], [1 2]) using logical indexing, we can do either this:
Ir = logical([1 1 0]);
Ic = logical([1 0 1]);
B = A(Ir, Ic)
or this:
I = logical([1 0 1; 1 0 1; 0 0 0]);
B = A(I)
or this:
I = logical([1 1 0 0 0 0 1 1 0]);
B = A(I)
Note that in the latter two cases is a one-dimensional vector, and should be reshaped back into a matrix if necessary (for example, using reshape).
Let me explain with an example:
Let's define a 6x6 matrix
A = magic(6)
A =
35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
4 36 29 13 18 11
From this matrix you want the elements in rows 1, 2 and 5, and in the columns 4 and 6
B = A([1 2 5],[4 6])
B =
26 24
21 25
12 16
Hope this helps.
function f = sub(A,i,j)
[m,n] = size(A);
row = 1:m;
col = 1:n;
x = row;
x(i) = [];
y=col;
y(j) = [];
f= A(x,y);
Returns the matrix A, with the ith row and jth column removed.

Find row-wise minima in sparse matrix

I would like to get the minimum nonzero values per row in a sparse matrix. Solutions I found for dense matrices suggested masking out the zero values by setting them to NaN or Inf. However, this obviously doesn't work for sparse matrices.
Ideally, I should get a column vector of all the row-wise minima, as I would get with
minValues = min( A, [], 2);
Except, obviously, using min leaves me with an all-zeros column vector due to the sparsity. Is there a solution using find?
This is perfect for accumarray. Consider the following sparse matrix,
vals = [3 1 1 9 7 4 10 1]; % got this from randi(10,1,8)
S = sparse([1 3 4 4 5 5 7 9],[2 2 3 6 7 8 8 11],vals);
Get the minimum value for each row, assuming 0 for empty elements:
[ii,jj] = find(S);
rowMinVals = accumarray(ii,nonzeros(S),[],#min)
Note that rows 4 and 5 of rowMinVals, which are the only two rows of S with multiple nonzero values are equal to the min of the row:
rowMinVals =
3
0
1
1 % min([1 9]
4 % min([7 4]
0
10
0
1
If the last row(s) of your sparse matrix do not contain any non-zeros, but you want your min row value output to reflect that you have numRows, for example, change theaccumarray command as follows,
rowMinVals = accumarray(ii,nonzeros(S),[numRows 1],#min).
Also, perhaps you also want to avoid including the default 0 in the output. One way to handle that is to set the fillval input argument to NaN:
rowMinVals = accumarray(ii,nonzeros(S),[numRows 1],#min,NaN)
rowMinVals =
3
NaN
1
1
4
NaN
10
NaN
1
NaN
NaN
NaN
Or you can keep using a sparse matrix with the fifth input argument, issparse:
>> rowMinVals = accumarray(ii,nonzeros(S),[],#min,[],true)
rowMinVals =
(1,1) 3
(3,1) 1
(4,1) 1
(5,1) 4
(7,1) 10
(9,1) 1

How to select a submatrix (not in any particular pattern) in Matlab

How to select a submatrix (not in any pattern) in Matlab? For example, for a matrix of size 10 by 10, how to select the submatrix consisting of intersection of the 1st 2nd and 9th rows and the 4th and 6th columns?
Thanks for any helpful answers!
TLDR: Short Answer
As for your question, suppose you have an arbitrary 10-by-10 matrix A. The simplest way to extract the desired sub-matrix would be with an index vector:
B = A([1 2 9], [4 6]);
Indexing in MATLAB
There's an interesting article in the official documentation that comprehensively explains indexing in MATLAB.
Basically, there are several ways to extract a subset of values, I'll summarize them for you:
1. Indexing Vectors
Indexing vectors indicate the indices of the element to be extracted. They can either contain a single index or several, like so:
A = [10 20 30 40 50 60 70 80 90]
%# Extracts the third and the ninth element
B = A([3 9]) %# B = [30 90]
Indexing vectors can be specified for each dimension separately, for instance:
A = [10 20 30; 40 50 60; 70 80 90];
%# Extract the first and third rows, and the first and second columns
B = A([1 3], [1 2]) %# B = [10 30; 40 60]
There are also two special subscripts: end and the colon (:):
end simply indicates the last index in that dimension.
The colon is just a short-hand notation for "1:end".
For example, instead of writing A([1 2 3], [2 3]), you can write A(:, 2:end). This is especially useful for large matrices.
2. Linear Indexing
Linear indexing treats any matrix as if it were a column vector by concatenating the columns into one column vector and assigning indices to the elements respectively. For instance, we have:
A = [10 20 30; 40 50 60; 70 80 90];
and we want to compute b = A(2). The equivalent column vector is:
A = [10;
40;
70;
20;
50;
80;
30;
60;
90]
and thus b equals 40.
The special colon and end subscripts are also allowed, of course. For that reason, A(:) converts any matrix A into a column vector.
Linear indexing with matrix subscripts:
It is also possible to use another matrix for linear indexing. The subscript matrix is simply converted into a column vector, and used for linear indexing. The resulting matrix is, however always of the same dimensions as the subscript matrix.
For instance, if I = [1 3; 1 2], then A(I) is the same as writing reshape(A(I(:)), size(I)).
Converting from matrix subscripts to linear indices and vice versa:
For that you have sub2ind and ind2sub, respectively. For example, if you want to convert the subscripts [1, 3] in matrix A (corresponding to element 30) into a linear index, you can write sub2ind(size(A), 1, 3) (the result in this case should be 7, of course).
3. Logical Indexing
In logical indexing the subscripts are binary, where a logical 1 indicates that the corresponding element is selected, and 0 means it is not. The subscript vector must be either of the same dimensions as the original matrix or a vector with the same number of elements. For instance, if we have:
A = [10 20 30; 40 50 60; 70 80 90];
and we want to extract A([1 3], [1 2]) using logical indexing, we can do either this:
Ir = logical([1 1 0]);
Ic = logical([1 0 1]);
B = A(Ir, Ic)
or this:
I = logical([1 0 1; 1 0 1; 0 0 0]);
B = A(I)
or this:
I = logical([1 1 0 0 0 0 1 1 0]);
B = A(I)
Note that in the latter two cases is a one-dimensional vector, and should be reshaped back into a matrix if necessary (for example, using reshape).
Let me explain with an example:
Let's define a 6x6 matrix
A = magic(6)
A =
35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
4 36 29 13 18 11
From this matrix you want the elements in rows 1, 2 and 5, and in the columns 4 and 6
B = A([1 2 5],[4 6])
B =
26 24
21 25
12 16
Hope this helps.
function f = sub(A,i,j)
[m,n] = size(A);
row = 1:m;
col = 1:n;
x = row;
x(i) = [];
y=col;
y(j) = [];
f= A(x,y);
Returns the matrix A, with the ith row and jth column removed.