- 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!