Matlab: Numerical array index into a string array (without loops)

假装没事ソ 提交于 2019-12-02 07:23:46

问题


I'm doing a set of problems from the MATLAB's introductory course at MIT OCW. You can see it here, it's problem number 9, part g.iii.

I have one matrix with the final grades of a course, all of them range from 1 to 5. And I have another array with only letters from 'F' to 'A' (in a 'decreasing' order).

I know how to change elements in a matrix, I suppose I could do something like this for each number:

totalGrades(find(totalGrades==1)) = 'F';
totalGrades(find(totalGrades==2)) = 'E';
totalGrades(find(totalGrades==3)) = 'C';
totalGrades(find(totalGrades==4)) = 'B';
totalGrades(find(totalGrades==5)) = 'A';

But then, what's the purpose of creating the string array "letters"?

I thought about using a loop, but we're supposed to solve the problem without one at that point of the course.

Is there a way? I'll be glad to know. Here's my code for the whole problem, but I got stuck in that last question.

load('classGrades.mat');
disp(namesAndGrades(1:5,1:8));
grades = namesAndGrades(1:15,2:size(namesAndGrades,2));
mean(grades);
meanGrades = nanmean(grades);
meanMatrix = ones(15,1)*meanGrades;
curvedGrades = 3.5*(grades./meanMatrix);

% Verifying 
nanmean(curvedGrades)
mean(curvedGrades)

curvedGrades(curvedGrades>=5) = 5;

totalGrades = nanmean(curvedGrades,2);

letters = 'FDCBA';

Thanks a lot!


回答1:


Try:

letters=['F','D','C','B','A'];
tg = [1 2 1 3 3 1];
letters(tg)

Result:

ans = FDFCCF

This works even when tg (total grade) is a matrix:

letters=['F','D','C','B','A'];
tg = [1 2 1 ; 3 3 1];
result = letters(tg);
result


result =                                                                                                                                                                             

FDF                                                                                                                                                                             
CCF

Edit (brief explanation):
It is easy to understand that when you do letters(2) you get the second element of letters (D).

But you can also select several elements from letters by giving it an array: letters([1 2]) will return the first and second elements (FD).

So, letters(indexesArray) will result in a new array that has the same length of indexesArray. But, this array has to contain numbers from 1 to the length of letters (or an error will pop up).



来源:https://stackoverflow.com/questions/35315097/matlab-numerical-array-index-into-a-string-array-without-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!