Getting this error : Operator '==' is not supported for operands of type 'cell'. what should I do?

73 次查看(过去 30 天)
function [ output_array ] = Klammer_Koordinate_Trennung( input_str )
for i= 1:length(input_str)
if input_str(i) == '('
index_1 = i;
end
if input_str(i) == ','
index_2 = i;
end
if input_str(i) == ')'
index_3 = i;
break;
end
end
output_array = [str2num(input_str(index_1 + 1 :index_2 - 1)),...
str2num(input_str(index_2 + 1 : index_3 - 1 ))];
end

回答(3 个)

Torsten
Torsten 2023-7-12

Dirk Engel
Dirk Engel 2023-7-12
Your function is designed to work when the input argument is a char vector, e.g. '(1,2)', but the error indicates that your function instead gets called with a cell array, e.g., {'(1,2)'}.
If the cell array contains a single char vector, you could add the following line to the top of your function to extract the char vector from the cell:
if iscell(input_str)
input_str = input_str{1}
end
If the cell arrray contains multiple elements, consider a second outer loop over the elements of the cell array.
Note that there are builtin ways to extract numbers from formatted text, such as sscanf() or textscan(). E.g.,
sscanf('(1.1,2.2)', '(%f,%f)', [1, 2])
extracts [1.1, 2.2] from the formatted string.

Michael Hubatka
Michael Hubatka 2023-7-12
Use regular expressions, for example
str2double(regexp("(1, 2)", "\d+", "match"))
ans = 1×2
1 2
for integer only and
str2double(regexp("(1.2, 3)", "\d+\.?\d*", "match"))
ans = 1×2
1.2000 3.0000
for floating point and integers.

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by