Display a value from a Matrix based on user input
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Guillaume
el 25 de Oct. de 2019
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 comentarios
Guillaume
el 29 de Oct. de 2019
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
Ver también
Categorías
Más información sobre Interpolation en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!