if statement in for loop with cell arrays

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

You wrote the test on the variable i which isn't even defined in your code...
if (i)<100 & (i)>=90
...
You need to test the score for each element in the struct score field, but you could do so without a loop as well...unless using for...end is part of the assignment, of course.
Guillaume
Guillaume 2019년 10월 29일
In addition, what is the purpose of the () brackets around i? They don't do anything at all, just make the code harder to read.
Note that the whole thing can be achieved in just one line by a call to discretize.
dpb
dpb 2019년 10월 29일
Also, those would be prime candidates to be categorical ordinal variables instead of character if we're looking a niceties... :)
Fabio Freschi
Fabio Freschi 2019년 10월 29일
Can you have char varaible as values in discretize?
Guillaume
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
Fabio Freschi 2019년 10월 29일

0 개 추천

To stick with the OP snippet
  1. I added semicolons all over the place
  2. I changed the variable type in s.score to doubles
  3. I preallocated the grades variable as string array
  4. I changed the check on (i) with s.score{i}
  5. I added <= 100 to include also the possibility of 100 score
  6. 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

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2019년 10월 29일

편집:

2019년 10월 30일

Community Treasure Hunt

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

Start Hunting!

Translated by