开发者

Find values in a matrix and put them into a vector

It must be simple, but surprisingly I couldn't find an answer to this problem here or by trial-and-error.

I want to get values out of a matrix (according to some condition) and place the values into a vector. I also need the subscript indices of the matching values. There is a 开发者_开发知识库lot of data so for loops are out.

This is a correct (but iterative) answer:

[I,J] = find(A > 5);
values = zeros(numel(I),1);
for i=1:numel(I)
    values(i) = A(I(i),J(i));
end

I tried values = A(I,J) but this is n-by-n instead of n-by-1.


You can implicitly treat the matrix like a vector (linear indexing):

I = find(A > 5);
values = A(I);

Note that you can do this more efficiently with logical indexing:

values = A(A > 5);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜