Adding to variable dependant on condition
Show older comments
i have a table and am checking if values lie within this range 60<=a<70, if they do i want to add 1 to another variable "x" so that x will represent the number of values within this range. using an elseif function how would i do this, thanks!
for a = 1:length(x)
if a >= 60 && a <70
6 Comments
Tommy
on 14 Apr 2020
How about just
x = sum(a >= 60 & a < 70)
Holden Earl
on 14 Apr 2020
Edited: Holden Earl
on 14 Apr 2020
Holden Earl
on 14 Apr 2020
Edited: Holden Earl
on 14 Apr 2020
It would give the number of values which are simultaneously over 60 and under 70, as
a >= 60 & a < 70
would return a logical array, containing a 1 at each value of a between 60 and 70 and a 0 at each other value.
Using an if-else statement would look something like this:
x = 0;
for a = range
if a >= 60 && a < 70
x=x+1
else
% do nothing
end
end
(edit after seeing your above comment) Make sure to reassign x with x+1. Additionally, it seems like x is playing two different roles in your code. If you are going to use
for a = 1:length(x)
then you might want to use a different variable for counting, such as
y=y+1;
Also note the else statement is unnecessary:
for a = 1:length(x)
if a >= 60 && a <70
y=y+1;
end
end
Walter Roberson
on 14 Apr 2020
You are calculating x+1 and throwing the result away instead of recording the result of the addition.
If a is the vector of values to be checked, you should probably not be using for a . You should probably be using an index into a, like for idx = 1 : length(a) and checking the value of a indexed at that variable.
Holden Earl
on 14 Apr 2020
Answers (0)
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!