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

前端 未结 1 953
一整个雨季
一整个雨季 2021-01-23 23:51

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

相关标签:
1条回答
  • 2021-01-24 00:38

    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).

    0 讨论(0)
提交回复
热议问题