How to make conditional calculation?
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Snoopy
am 24 Feb. 2018
Kommentiert: Image Analyst
am 25 Feb. 2018
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
0 Kommentare
Akzeptierte Antwort
Image Analyst
am 24 Feb. 2018
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 Kommentare
Image Analyst
am 25 Feb. 2018
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.]
Weitere Antworten (1)
Walter Roberson
am 24 Feb. 2018
if M(:,1) < 0
means the same thing as
if all(M(:,1) < 0)
which is probably not true.
Look up "logical indexing"
2 Kommentare
Walter Roberson
am 24 Feb. 2018
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
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!