if statement in for loop with cell arrays
11 次查看(过去 30 天)
显示 更早的评论
I have this problem with matlab, I have to assign letter grades to the scores I have, but I couldn't do it. Can anybody help?
s.name={'Seda','Ayça','Deniz','Kerem','Mete'}
s.score={'90','45','68','86','82'}
N=lenght(s.score)
for i = 1:1:N
if (i)<100 & (i)>=90
grades(i)='A'
elseif (i)<90 & (i)>=80
grades(i) ='B'
elseif (i)<80 & (i)>=70
grades ='C'
elseif (i)<70 & (i)>=60
grades ='D'
else
grades = 'F'
end
end
5 个评论
Guillaume
2019-10-30
编辑:Guillaume
2019-10-30
Can you have char varaible as values in discretize?
Yes,
>> score = [90, 45, 68, 86, 82];
>> discretize(score, [0 60 70 80 90 100], {'F', 'D', 'C', 'B', 'A'})
ans =
1×5 cell array
{'A'} {'F'} {'D'} {'B'} {'B'}
All discretize does is index the values array with the indices it would normally return. You can have pretty much anything that can be indexed as values.
回答(1 个)
Fabio Freschi
2019-10-29
To stick with the OP snippet
- I added semicolons all over the place
- I changed the variable type in s.score to doubles
- I preallocated the grades variable as string array
- I changed the check on (i) with s.score{i}
- I added <= 100 to include also the possibility of 100 score
- I changed the single & to double && for logical scalar values
s.name={'Seda','Ayça','Deniz','Kerem','Mete'};
s.score={90,45,68,86,82};
N=length(s.score);
grades = strings(N,1);
for i = 1:1:N
if s.score{i}<=100 && s.score{i}>=90
grades(i)='A';
elseif s.score{i}<90 && s.score{i}>=80
grades(i) ='B';
elseif s.score{i}<80 && s.score{i}>=70
grades(i) ='C';
elseif s.score{i}<70 && s.score{i}>=60
grades(i) ='D';
else
grades(i) = 'F';
end
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!