Display a value from a Matrix based on user input

조회 수: 9 (최근 30일)
James Knight
James Knight 2019년 10월 25일
댓글: Guillaume 2019년 10월 29일
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

답변 (1개)

Guillaume
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, ','));
The key function to looking up multiple keys at once is ismember.
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
James Knight
James Knight 2019년 10월 29일
It only accepts blocks of 4
Guillaume
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by