Warm tip: This article is reproduced from serverfault.com, please click

Matlab Structures: How to compare the contents of structure? Getting the following error

发布于 2020-11-30 00:52:59

I have the structure below with the value. When I try to compare the value of the field I get the error below. What can I do?

Input

XYZ.Element_2 =='Fundamental'
if XYZ.Element_2 == 'RMS'
    var33=1
else
    var33=0
end

Output

Matrix dimensions must agree.

Error in sample50main (line 38)
if XYZ.Element_2 == 'RMS'
Questioner
Vinod
Viewed
0
MichaelTr7 2020-11-30 14:25:53

Looks like the issue is that MATLAB is trying to do a character array comparison and since those arrays do not have an equal number of characters a dimension error is thrown. An implementation that could resolve this may be by doing a string comparison using double quotes "". Alternatively, you can use the strcmp() function as described in the comment above. Below are both implementations:

Method 1: Using Double Quotes

Condition True:

XYZ.Element_2 = 'Fundamental';

if XYZ.Element_2 == "RMS"
    var33 = 1;
else
    var33 = 0;
end

Condition False:

XYZ.Element_2 = 'RMS';

if XYZ.Element_2 == "RMS"
    var33 = 1;
else
    var33 = 0;
end

Method 2: Using strcmp() Function

Condition True:

XYZ.Element_2 = 'Fundamental';

if strcmp(XYZ.Element_2,'RMS')
    var33 = 1;
else
    var33 = 0;
end

Condition Flase:

XYZ.Element_2 = 'RMS';

if strcmp(XYZ.Element_2,'RMS')
    var33 = 1;
else
    var33 = 0;
end

Ran using MATLAB R2019b