필터 지우기
필터 지우기

Assign column index to output value

조회 수: 1 (최근 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