- 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 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Jaynik
2024-11-8,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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!