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.

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by