'Matrix dimensions must agree' error on string operations

3 次查看(过去 30 天)
My code looks like:
data is 2x1 array.
data =
{'cont_box_A'}
{'cont_box_B'}
I'm trying to compare the string to another string, like:
if(data{1} == 'Test')
fprintf('Not the same')
else
fprintf('Same')
end
When I try to execute this, I get an error saying 'Matrix dimensions must agree'. don't really know what's wrong.

采纳的回答

Stephen23
Stephen23 2020-6-10
"...don't really know what's wrong."
What you wrote performs an element-wise comparison of the character in two character arrays. Just like for numeric arrays, that operation requires that the arrays have compatible sizes (exactly as described in the documentation, so I won't copy it here).
But what you are trying to do is to compare the entire strings, for which you should use strcmp or strcmpi:
strcmp(data{1},'Test')

更多回答(1 个)

madhan ravi
madhan ravi 2020-6-10
ismember(data{1}, 'Test')

类别

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

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by