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!