ram*_*ker 2 matlab switch-statement
我正在尝试编写一个函数,将单元格数组中每个东西的类,长度和值放入结构中,但是我一直在使用switch语句出错
function [ out, common ] = IDcell( cA )
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
cl={};
val={};
len={};
for x=1:length(cA)
switch cA(x)
case isnum
cl(x)='double';
case ischar
cl(x)='char';
case islogical
cl(x)='logical';
case iscell
cl(x)= 'cell';
end
val=[val cA{x}];
len=[len size(value(x))];
end
out=struct('value', val, 'class', cl, 'length', len);
end
[out]=IDcell(cA)
SWITCH expression must be a scalar or string constant.
Error in IDcell (line 8)
switch cA(x)
Run Code Online (Sandbox Code Playgroud)
isnum不是Matlab函数. isnumeric可能是你在想什么,但它不是你输入的.这意味着你的代码正在看到case isnum它并且它不知道isnum它是什么,所以它告诉你它是什么,如果你想在那里使用它你需要使它成为一个评估为数字的东西(标量意味着什么)或一段文字(字符串常量意味着什么).
此外,ischar是一个matlab函数,但你没有正确使用它.你必须使用它ischar(cA(x)),例如,然后评估trueif cA(x)是一个字符串或文本片段,将评估falseif是否cA(x)是其他任何东西.
虽然如果以switch这种方式工作会很可爱,但事实并非如此.你不能把东西放在switch零件中,然后只列出需要在switch零件中对那件东西进行评估的函数 .
你可以做的事情是这样的:
switch class(x)
case 'double'
fprintf('Double\n');
case 'logical'
fprintf('Logical\n');
end
Run Code Online (Sandbox Code Playgroud)
在这里,我以需要使用的class方式使用了函数,其中包含一个参数.然后我根据该函数的输出切换我的案例,类输出一个字符串.