Why is the function "isequal" giving wrong answer when comparing string fields of two structure arrays?
Mostrar comentarios más antiguos
I have two structure arrays, say x and y. Each structure has two fields: name and data. Assume for example that:
x(1).name = 'name1'; x(2).name = 'name2';x(1).data = [1,2];x(2).data = [1,2];
y(1).name = 'name1'; y(2).name = 'name2';y(1).data = [1,2];y(2).data = [1,2];}
Now, the two structure arrays are identical. When I use "isequal" to compare x.data and y.data as following:
isequal(x.data,y.data) it gives logic 1 output.
But, when I use "isequal" to compare x.name and y.name, it gives logic 0 output, although they are identical. Is this a problem in the function "isequal"? And, what can I do to compare x.name and y.name correctly?
2 comentarios
"Now, the two structure arrays are identical. "
Sure.
"But, when I use "isequal" to compare x.name and y.name, it gives logic 0 output, although they are identical."
Sure. Because with your syntax you are not comparing those structures.
"Is this a problem in the function "isequal"?"
Nope, it is a problem with your code. The cause is very simple: this syntax
x.data
x.name
x(1).data, x(2).data, ..., x(end).data
x(1).name, x(2).name, ..., x(end).name
which means your code is exactly equivalent to this:
isequal(x(1).data, x(2).data, ..., x(end).data, y(1).data, y(2).data, ..., y(end).data)
isequal(x(1).name, x(2).name, ..., x(end).name, y(1).name, y(2).name, ..., y(end).name)
which is thus equivalent to this (using your example data):
isequal([1,2], [1,2], [1,2], [1,2]) % all equal -> true
isequal('name1', 'name2', 'name1', 'name2') % all equal -> false
which according to the isequal help, " tf = isequal(A1,A2,...,An) returns logical 1 (true) if all the inputs are numerically equal." Are all of your multiple inputs numerically equal? In the first case they are, thus the true output, in the second case they are not, thus the false output. Thus there is no problem with isequal, it is doing exactly what it is documented to do.
To learn more about comma-separated lists:
"And, what can I do to compare x.name and y.name correctly?"
You can resolve this by putting the fields into one array, e.g. a cell array as jonas showed, or by simply comparing the complete structures.
Mohamed Abd El Raheem
el 5 de Ag. de 2018
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!