MATLAB: How can turn cells to string

casecell

I have a list of cells that contain string and i want to try to find if it contain a specify string. i have 4 possibility and on each of them i do something else. i can do in with if-else (a simple example add above). How i can do it but with switch?
a = {'pass' 1;'hp' 1;'C2C' 200; 'hC2C' 200; 'C2C TO' 534; 'hC2C' 534; 'C2C TO' 534; ...
'hp' 1001; 'pass' 1001; 'pass' 1001};
d = [1 200 534 1001];
for i=1:length(d)
if sum(strcmp(a(cell2mat(a(:,2))==d(i)),'pass')) ~= 0
fprintf('It''s a Passive\n')
elseif sum(strcmp(a(cell2mat(a(:,2))==d(i)),'C2C')) ~= 0
fprintf('It''s a C2C\n')
elseif sum(strcmp(a(cell2mat(a(:,2))==d(i)),'C2C TO')) ~= 0
fprintf('It''s a C to C\n')
end
end

Best Answer

It is my understanding that you would like to use "switch-case" instead of "if-else" to avoid verbose statements. I am not able to figure out a straightforward way to use "switch-case", but the code may be simplified by implementing the string matching part inside a function. For example, define:
function str = stringMatching(cellarray, dvalue)
% "stringList" and "outputList" must be of the same size
stringList = {'pass', 'C2C', 'C2C TO'}; % A list of strings that need to be matched
outputList = {'Passive', 'C2C', 'C to C'}; % The output of the corresponding string in "stringList"
str = ''; % Initialize output
stringInCell = cellarray(:, 1); % put the strings in one cell array
% Use "ind" for the output of "cell2mat(a(:, 2)) == d(i)" in the original code
ind = (cell2mat(cellarray(:, 2)) == dvalue);
% The following loop tests if strings in "stringList" have any match in "cellarray"
% This loop replaces the multiple "if" statements in the original code.
for i = 1 : numel(stringList) % Iterate through all the elements in "stringList"
% Use "ismember" instead of "strcmp" to test if the string can be found in "cellarray"
if (ismember(stringList{i}, stringInCell(ind))
str = outputList{i};
break;
end
end
Please note that "ismember" is used instead of "strcmp". You can refer to the following documentation for more information on "ismember":
In addition, I use "stringList" to store all the strings that needs to be found in the cell array, and "outputList" to specify the corresponding output strings. Therefore, if you need to match more strings, only "stringList" and "outputList" need to be changed.
With the above function, you may rewrite the "for" loop as follows:
for i = 1 : length(d)
str = stringMatching(a, d(i));
if ~isempty(str)
fprintf('It''s a %s\n', str);
end
end