How to make an else if statement with multiple lines to execute

25 ビュー (過去 30 日間)
Dimitra Kofterou
Dimitra Kofterou 2018 年 12 月 29 日
コメント済み: Walter Roberson 2018 年 12 月 29 日
I want to write an if statement with elseif, and i want to execute multiple lines when the else if is true.
My code is like this
k=1;
m=1;
for i=1:length(a)
if a(i)==b
possitionb(k)=a(i);
timeb=timea(i);
k=k+1;
else
% i want this 3 lines to be executed only when else happens
possitionfound(m)=a(i);
time(m)=alltimes(i);
m=m+1;
end
end
I know this might be a pretty silly question, but i can't find the way to run it correctly...
Thank you in advance!
  1 件のコメント
Walter Roberson
Walter Roberson 2018 年 12 月 29 日
your code would fail if b is not scalar (unless the values were identical for all entires)

サインインしてコメントする。

回答 (1 件)

vik
vik 2018 年 12 月 29 日
I tried to write an example that matches your described code. t is a vector containing 0.1, 0.2, ... and so on as time-data and a is a value to be checked. k, m and n are counters which will indicate how often the numbers b and c or none of them were found.
You can simply use if, elseif and else. If you start counters at zero you can see how often your condition was met and the code got executed:
clear variables
% Create some Data for example:
t = 0.1:0.1:0.9; % Some "time" data
a = [1,3,4,2,4,2,2,5,3]; % Some more data
b = 2; % Thing to search for
c = 4; % Another thing for elseif
% Start Counters at Zero
k = 0;
m = 0;
n = 0;
for idx = 1:length(a)
if a(idx) == b
k = k+1;
position_b(k) = idx;
time_b(k) = t(idx);
elseif a(idx) == c
% This gets executed if first if-thing was false
% and the condition a(idx) == c is true
m = m+1;
position_c(m) = idx;
time_c(m) = t(idx);
else
% This gets executed only if both conditions
% above were false
n = n+1;
position_else(n) = idx;
time_else(n) = t(idx);
end
end
Note that if you set both b and c to the same value (for example "2"), the elseif statement will not get called, even if the condition is true.
  1 件のコメント
Dimitra Kofterou
Dimitra Kofterou 2018 年 12 月 29 日
Ok, i think i find out what is going on, thank you!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by