- input: https://www.mathworks.com/help/matlab/ref/input.html
- containers.Map: https://www.mathworks.com/help/matlab/ref/containers.map.html
- isKey: https://www.mathworks.com/help/matlab/ref/containers.map.iskey.html
how can i store input characters from user and every time when get new input compare it with already stored values if present already then give error message?
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I want to get input characters from user and store it in an array or any other storing elements in matlab, and while loop is running so every time when new character from user is get, it is first compared with the already stored characters, if present in the array already, an error message is generated. This input will be used in switch statement later.
0 Kommentare
Antworten (1)
Jaynik
am 8 Nov. 2024 um 7:11
Hi Samia,
You can follow two approaches here but the overall steps remain the same. We can initialize an empty data structure to store the characters. Then we obtain the input from the user using the input function. We check the data structure for the input and proceed with the code.
Approach 1: Using while loop and array as suggested by you
storedChars = [];
while true
newChar = input('Enter a character: ', 's');
% Check if the character is already in the array
if any(storedChars == newChar)
disp('Character already entered.');
else
% Add the new character to the array
storedChars = [storedChars, newChar];
switch newChar
% Your code
end
end
end
Approach 2: Using isKey and container.Map
storedChars = containers.Map('KeyType', 'char', 'ValueType', 'logical');
while true
newChar = input('Enter a character: ', 's');
% Check if the character is already in the map
if isKey(storedChars, newChar)
disp('Character already entered.');
else
% Add the new character to the map
storedChars(newChar) = true;
switch newChar
% Your code
end
end
end
Please refer the following documentation to read more about these:
Hope this helps!
0 Kommentare
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!