Adding to variable dependant on condition
显示 更早的评论
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 个评论
Tommy
2020-4-14
How about just
x = sum(a >= 60 & a < 70)
Holden Earl
2020-4-14
编辑:Holden Earl
2020-4-14
Holden Earl
2020-4-14
编辑:Holden Earl
2020-4-14
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
2020-4-14
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
2020-4-14
回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!