Assign column index to output value

6 次查看(过去 30 天)
Rachel McMurphy
Rachel McMurphy 2019-11-20
编辑: Jan 2019-11-20
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 个评论
Jan
Jan 2019-11-20
编辑:Jan 2019-11-20
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.

请先登录,再进行评论。

回答(1 个)

Jan
Jan 2019-11-20
编辑:Jan 2019-11-20
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

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by