How to find the non-zero minimum of a subset of matrix elements

조회 수: 2 (최근 30일)
2Lindsay2
2Lindsay2 2020년 6월 24일
답변: Sindar 2020년 6월 25일
I'm trying to find the non-zero miumum of a subset of elements in a matrix in a similar manner to that of using
minimum = min(A(A>0))
As an example, what I have is
A = [1 2 3 4; 2 0 1 5; 0 3 2 5; 1 2 1 0];
subsetOfRows = [1 2 4];
column = 2;
minimum = min(A(A(subsetOfRows,column)>0))
so I want the non-zero minimum of comumn 2 while just comparing the first, second, and fourth row elements. The answer I'm looking for is 2, but the answer I get is 0. Does anyone know how to implement this? Or is there a better way to go about doing this?
Thank you in advance

채택된 답변

Sindar
Sindar 2020년 6월 25일
The issue is that logical indexing doesn't work when you are checking against a subset of the matrix:
>> A = [1 2 3 4; 2 0 1 5; 0 3 2 5; 1 2 1 0];
>> subsetOfRows = [1 2 4];
>> column = 2;
>> A(subsetOfRows,column)
ans =
2
0
2
>> A(subsetOfRows,column)>0
ans =
3×1 logical array
1
0
1
>> A(A(subsetOfRows,column)>0)
ans =
1
0
What's happening is that you extract the first, (not second), and third elements of A, instead of pulling out the full index from the subset. There may be some clever trick to do this in one step, but this will get it done in cases where the subset of A is not overly large
A = [1 2 3 4; 2 0 1 5; 0 3 2 5; 1 2 1 0];
subsetOfRows = [1 2 4];
column = 2;
tmp = A(subsetOfRows,column);
minimum = min(tmp(tmp>0));

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by