How to make conditional calculation?

조회 수: 4 (최근 30일)
Snoopy
Snoopy 2018년 2월 24일
댓글: Image Analyst 2018년 2월 25일
I have two vectors, contained in matrix M, each with a dimension of 1000 by 1. Each vector contains integer numbers. The values in one vector (call it vector two) is generated in way that it depends on the values in the other vector (call it vector one). I want to calculate the variance of the numbers in vector two if the values are below a certain threshold in vector one. I try to use the code below, but it returns nothing. Where am I making the mistake?
if M(:,1) < 0
var(M(:,2))
end

채택된 답변

Image Analyst
Image Analyst 2018년 2월 24일
Maybe you mean this:
indexesToConsider = M(:, 1) < 0; % Consider the index if the M value is less than 0.
col2Variance = var(M(indexesToConsider, 2)); % Compute variance of only those rows.
  댓글 수: 2
Snoopy
Snoopy 2018년 2월 24일
This the logical indexing Walter above mentions right? I now use it. Thanks a lot.
Image Analyst
Image Analyst 2018년 2월 25일
Yes, it's logical indexing in that it gives values of true and false. If you passed that into find() you'd get "linear indexes" which are the actual index numbers, like [1, 3, 5, 33, 45, etc.] instead of [1 0 1 0 1 0 0 etc.]

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2018년 2월 24일
if M(:,1) < 0
means the same thing as
if all(M(:,1) < 0)
which is probably not true.
Look up "logical indexing"
  댓글 수: 2
Snoopy
Snoopy 2018년 2월 24일
Thanks. I now use the find function which returns the row numbers (or the row index I shall say?) where the condition for vector one is satisfied. Then I use these row numbers as the row subscript in vector two, and carry out the operation on this subset of the entries of vector two. Is this perhaps the correct approach?
Walter Roberson
Walter Roberson 2018년 2월 24일
That is one approach, but it is more efficient to use logical indexing. https://www.mathworks.com/help/matlab/math/matrix-indexing.html#bq7egb6-1

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by