Not overwriting array in if-elseif loop

Hi,
I have the following code
for k = 1:length(yarray)-1
if yarray(k+1) <= A & yarray(k) >= A
M = [yarray(k) yarray(k+1) k k+1]
elseif yarray(k+1) >= A & yarray(k) <= A
M = [yarray(k) yarray(k+1) k k+1]
end
end
Where yarray is an array of y values in a plot, and A is the y value that I want to find corresponding x values to. I am expecting the if and elseif conditions to be satisfied 4 times, resulting in 4 M arrays. However, each time this is satisfied, M is overwritten. How can I come up with 4 different arrays which I can recall later?Let me know if this needs more clarification. Thanks!

 採用された回答

Oleg Komarov
Oleg Komarov 2011 年 7 月 23 日

0 投票

Preallocate M before the loop and index it inside the loop:
M = zeros(length(yarray)-1,4);
for...
M(k,:) =
end

その他の回答 (1 件)

Jan
Jan 2011 年 7 月 23 日

0 投票

y_le_A = (yarray <= A);
y_ge_A = (yarray >= A);
index = or(and(y_le_A(2:end), y_ge_A(1:end-1)), ...
and(y_ge_A(2:end), y_le_A(1:end-1)));
k = find(index);
M = transpose([yarray(k); yarray(k+1); k; k+1]);
The last line needs yarray to be a row vector.
I have the impression, that this can be simplified using a DIFF trick.

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by