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

60 Ansichten (letzte 30 Tage)
Dimitra Kofterou
Dimitra Kofterou am 29 Dez. 2018
Kommentiert: Walter Roberson am 29 Dez. 2018
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 Kommentar
Walter Roberson
Walter Roberson am 29 Dez. 2018
your code would fail if b is not scalar (unless the values were identical for all entires)

Melden Sie sich an, um zu kommentieren.

Antworten (1)

vik
vik am 29 Dez. 2018
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.

Kategorien

Mehr zu File Operations 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!

Translated by