I’m trying to write a function that puts the class, length, and value of each of the things in a cell array into a struct, but I keep getting an error with the switch statements
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)
isnumis not a Matlab function.isnumericmay be what you were thinking of, but it isn’t what you typed. Which means your code is seeingcase isnumand it has no idea what the heckisnumis, so it is telling you whatever it is, if you want to use it there you need to make it something that evaluates to a number (what it means by scalar) or to a piece of text (what it means by string constant).Further,
ischaris a matlab function, but you are not using it the right way. You must use it asischar(cA(x))for example, will then evaluate totrueifcA(x)is a string or snippet of text, will evaluate tofalseifcA(x)is anything else.While it would be lovely if
switchworked this way, it doesn’t. You can’t put a thing in theswitchpart, and then just list functions that need to be evaluated on that thing in theswitchpart.The kind of thing you can do is this:
Here I have used the
classfunction the way it needs to be used, with an argument in it. And I then switch my cases based on the output of that function, class outputs a string.