Error on Switch/case with cell array char data

Hello I am getting "SWITCH expression must be a scalar or a character vector." when i run my code bellow. I want to take an typed input from the user split it into individual cells and then check the variable with the created switch case concatenating the resulting letter's probability into a new variable. I know it has something to do to converting the inputted cell values into a character vector but I haven't found any good way to do it. Any help would be appreciated
get = input('type(letters only, no puncuation): ' , 's');
split = num2cell(get);
sorted_split = sort(split);
input_prob = [];
for n = 1 : length(sorted_split)
switch sorted_split{n}
case ' '
horzcat(input_prob,0.1859);
case 'a'
horzcat(input_prob,0.0642);
case 'b'
horzcat(input_prob,0.0127);
end
end
...

댓글 수: 2

Your code runs for me without giving the error message you mention. Can you share exactly what you are using for input to create the error? Also, please copy/paste the error message here (all the red text). I wonder if the error may be coming from code that you have not shared here.
James Wang
James Wang 2020년 11월 21일
편집: James Wang 2020년 11월 21일
My apologies I have forgotten that I have been playing around with parfor loops for no real reason expect for speed. the error message that is given is
Error using fff (line 9)
SWITCH expression must be a scalar or a character vector.
%#ok<*MFAMB>
tic
close all
get = input('type(letters only, no puncuation): ' , 's');
split = num2cell(get);
input_prob = [];
parfor n = 1 : length(split)
switch split(n)
case ' '
horzcat(input_prob,0.1859);
case 'a'
horzcat(input_prob,0.0642);
case 'b'
horzcat(input_prob,0.0127);
case 'c'

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

 채택된 답변

James Wang
James Wang 2020년 11월 21일
After looking at multiple answer i have solved my question. I have removed the parfor loop that was there and used Vasishta Bhargava answer for the switch case. Thank you all for your help
close all
get = input('type(letters only, no puncuation): ' , 's');
split = char(lower(get));
input_prob = [];
for n = 1 : length(split)
switch split(n)
case ' '
input_prob = horzcat(input_prob,0.1859);
case 'a'
input_prob= horzcat(input_prob,0.0642);
case 'b'
input_prob = horzcat(input_prob,0.0127);
case 'c'
input_prob = horzcat(input_prob,0.0218);
case 'd'

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

릴리스

R2019b

질문:

2020년 11월 21일

답변:

2020년 11월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by