Assign column index to output value
1 view (last 30 days)
Show older comments
I'm creating a function where I take a submatrix and determine what elements are nonzero. Then I must assign the column index of the first nonzero element as an output value. Here is my code:
function s = search(M,i) %M is matrix, i is row
[n,m] = size(M); %n is rows, m is columns
submatrix = M([i:n],[1:m]); %output is rows below and equal to i
column_index = any(submatrix); %gives logical array of nonzero elements
end
%Matrix used as example
M = [1 3 2 -4 1 10 -3; ...
0 0 1 -2 0 4 0; ...
0 0 2 -4 1 7 -2; ...
0 0 -3 6 -2 -10 4]
Using M as an example, if I do search(M,2), my final output should be '3' meaning the 3rd column of the submatrix is the first column which has nonzero elements. I'm unsure how to make it so with any matrix the output is the first nonzero column.
1 Comment
Jan
on 20 Nov 2019
Edited: Jan
on 20 Nov 2019
For the shown M, the submatrix for i=2 is:
M = [2 -4 1 10 -3; ...
1 -2 0 4 0; ...
2 -4 1 7 -2; ...
-3 6 -2 -10 4]
Why do you assume, that its 3rd column is the first column, which has nonzero elements? The 1st column has nonzero elements already. But this is the 3rd column of the original matrix. The 3rd column of the submatrix contains a zero element. So please explain exactly, what is wanted.
Answers (1)
Jan
on 20 Nov 2019
Edited: Jan
on 20 Nov 2019
An easier way to create the submatrix:
submatrix = M(i:end, :);
The any() operates along the first non-singelton dimension. For a [1 x n] vector, this replies a scalar. So specify the dimension to operate on explicitly:
column_index = any(submatrix, 1);
Now you need the find() command, to find the first non-zero value:
s = find(couumn_index, 1);
This can be joined to one line:
function s = search(M,i) %M is matrix, i is row
s = find(any(M(i:end, :), 1), 1); % Maybe you want add the value of i?!
end
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!