How can I get a string from an input to be used to index an array?

5 次查看(过去 30 天)
So I'm trying to write this code that I want to act as a music scale key for various different keys. The code asks the user to input the key and mode they want to practice in (i.e E major) and it'll spit out the correct scale for that key and mode, so for E major it will print E F# G# A B C# D#.
major = [1 3 5 6 8 10 12]; % an array to index chromatic array for major scale notes
chromatic = ["C", "C#", "D", "D#", "E", "F", "F#", "G", ...
"G#", "A", "A#", "B"];
key = input('Try again, what key do you practice in?\n', 's');
key_split = strsplit(key);
S = char(key_split);
if contains(S(1,:), 'b')
chromatic = chromatic_flats;
mode = S(2,:);
else
chromatic = chromatic_sharps;
mode = S(2,:);
end
k = find(strcmp(key_split(1), chromatic));
% Strcmp passes T/F to the chromatic array and find finds the corresponding array index
chromatic = circshift(chromatic, 13 - k);
% Cicshift shifts the chromatic array to start at the key choosen from
fprintf('\nPracticing in the key of %s %s\n', char(key_split(1)), char(mode))
practice_key = chromatic(mode)**
So I only really need help with the last line of code that I double starred, everything above that is the code to change the chromatic scale to start with they key the user selected. I know the input from the user is a string and I can't index an array with a string, so I can't find the right solution to that. I've looked up structures and cell arrays but not sure how to implement them if they are the correct solution.

回答(1 个)

Patrick Eschbach
Patrick Eschbach 2017-8-4
Hi Michael,
It looks like you want to return a subset of your array of notes, i.e., a portion of the chromatic data structure, depending on the key and mode the user inputs. If you just want to return the portion of the chromatic structure starting at a particular note, you could use strfind to find the starting index of a string inside chromatic and then index with that number.
See info about strfind: https://www.mathworks.com/help/matlab/ref/strfind.html
Example: practice_key = chromatic(strfind(chromatic, mode), :);
If you really want to index with a string, you should look into mapping string keys to some other sort of value using the map class. See info about the map class: https://www.mathworks.com/help/matlab/ref/containers.map-class.html
I do not think it would be necessary to use cell arrays or structures for this particular problem.
-Pat

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by