Switch case with cell gives an error
조회 수: 1 (최근 30일)
이전 댓글 표시
I have this switch case but gives me an error because str is a cell. What can I do to correct it? The str is a cell 1x2.
str(1)='Yes'
str(2)='No'
str=get(g.rd,'string');
switch str
case 'Yes'
state='yes';
case 'No'
state='no';
end
댓글 수: 0
답변 (2개)
Walter Roberson
2013년 5월 31일
str(1) = {'Yes'}
or
str{1} = 'Yes';
Your code would have failed on the first assignment.
When you get() the 'string' property from g.rd, is the result a character vector (string) or a character array (such as can occur if you have multiple lines in the string property) or is it going to be a cell array of strings?
Are you certain that the 'string' property will contain exactly one row?
Is there a reason you are not using
state = lower(str) %assuming str is a character vector
댓글 수: 0
Giorgos Papakonstantinou
2013년 5월 31일
댓글 수: 2
Walter Roberson
2013년 5월 31일
Is there any point in getting the val of g.rd(1) and g.rd(2) but then only making use of the first value?
If the result of get(g.rd,'string') is a cell array of strings, {'Yes', 'No'} then getting just the string does not tell you anything about the state.
Accessing the Value rather than the String is the right thing to do. The "if" you have just above is fine.
Have you considered using a toggle button or radio button, instead of two push buttons in a uibuttongroup ?
But if you really want to see an example of switching on a string, then:
function hide(varargin)
g = varargin{3};
str1 = cellstr( get(g.rd(1), 'string') );
str2 = cellstr( get(g.rd(2), 'string') );
str2 = {str1{1}; str2{1}};
%choice should come out 1 if the first button was selected, 2 if the second button was selected
choice = get(g.rd(1), 'Value') + 2 * get(g.rd(2), 'Value');
str = str12{choice};
switch str
case 'Yes'
state='yes';
case 'No'
state='no';
end
assignin('base', 'st', state);
The above is not how I would bother to code it, considering it can be done like
function hide(varargin)
g = varargin{3};
st = get(g.rd(1), 'Value');
str12 = {'yes'; 'no'};
state = str12{2 - st};
assignin('base', 'st', state);
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!