Display a value from a Matrix based on user input
5 ビュー (過去 30 日間)
古いコメントを表示
Hi I have a matrix , if the user enters '1234' at userinput I would like the output to be the next cell along or '5678' B etc. etc.
is this possible? I would also like the user to be able to type in more than one number at a time (the numbers are always blocks of four) EG if they type '12345678' the output would be AB
Thanks
for counter = 1:4:length(userinput)
end
mykey= ["1234","A";"5678","B"];
userinput= input ('enter your numnber')
output= XXXXXXX
0 件のコメント
回答 (1 件)
Guillaume
2019 年 10 月 25 日
Note that your mykey is a string array. We typically use the term matrix only when referring to numeric arrays.
Also note that "1234" is not a number. It's the textual representation of a number. It would indeed be better if you stored the numbers as actual numbers rather than text, eg:
mymap = containers.Map([1234, 5678], ["A", "B"]);
or
mytable = table([1234; 5678], ["A"; "B"], 'VariableNames', {'key', 'value'});
Either of these make it trivial to retrieve the value associated with a key:
%using containers.Map
searchkey = input('Enter a single number');
if isKey(mymap, searchkey)
fprintf('The value matching key %d is: %s\n\n', searchkey, mymap(searchkey)); %mymap(searchkey) returns the corresponding value
end
searchkeys = input('Enter an array of number')
[found, whichindex] = ismember(searchkeys, mymap.Keys);
keysfound = searchkeys(found);
matchingvalues = mymap.Values(whichindex(found));
fprintf('These numbers were found: [%s]\n', strjoin(compose('%d', keysfound), ', '));
fprintf('Matching values are: [%s]\n\n', strjoin(matchingvalues, ', '));
%using a table
searchkeys = input('Enter one or more number');
[~, where] = ismember(searchkeys, mytable.key);
keysfound = mytable.key(where);
matchingvalues = mytable.values(where);
fprintf('These numbers were found: [%s]\n', strjoin(compose('%d', keysfound), ','));
fprintf('Matching values are: [%s\n\n', strjoin(matchingvalues, ','));
Note that all of the above works even if the keys are actually strings but storing numbers as numbers is more efficient (faster comparison, less memory used).
4 件のコメント
Guillaume
2019 年 10 月 29 日
searchkeys = input('some prompt', 's')
assert(mod(numel(searchkeys), 4) == 0, 'length of key myst be a multiple of 4');
searchkeys = mat2cell(searchkeys, repelem(4, numel(searchkeys)/4)); %split into char vectors of length 4
%... use ismember or other as above
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!