Reodering/Swapping Arrays in a struct
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Chris Dan
am 19 Okt. 2019
Bearbeitet: Chris Dan
am 19 Okt. 2019
Hello Everyone, I am new to matlab. I am having a problem which is reodering the arrays in a structure by taking in user input.
What I mean is user will enter some values in a vector and according to them, arrays in the struct should be reodered.
As you can see in the pictures, the vector given by the user is 1x7 and the struct is 7x1 and I want to reoder the arrays in the struct according to the vector.
My vector is named as "a" and the struct is named as "out"
Now my code is:
for i = 1:7
a(i) = input('Input a number: ');
if (a(i) > 7)
{ error('Value exceeds the Number of Struct Rows')
}
end
end
for i =1:7
out(a(i)) == out(i)
end
this is a vector givien by the user
this is the struct, which I have
The error I am getting is
"Undefined operator '==' for input arguments of type 'struct'."
I donnot know how to resolve it or what is wrong in my code
0 Kommentare
Akzeptierte Antwort
Guillaume
am 19 Okt. 2019
You seem to be writing matlab code using C syntax. In matlab if conditions don't need to be enclosed in () brackets
if a(i) > 7
and more importantly the body of if must not be enclosed in {}
{ error('Value exceeds the Number of Struct Rows')
}
attempts to create a cell array containing the output of error and since error doesn't have any output, the actual error message produced by the above would be: Error using error. Too many output arguments.
So, that part should be:
if a(i) > 7
error('Value exceeds the Number of Struct Rows');
end
or more simply
assert(a(i) <= 7, 'Value exceeds the Number of Struct Rows')
Even better get rid of the loop:
a = input('Enter a vector of seven numbers using [1 2 3 4 5 6 7] syntax:');
assert(all(a <= 7), 'At least one value exceeds the number of rows');
In C and in matlab == is the comparison operator, not the assignment. Matlab doesn't know how to compare structure.
Once again, a loop is not needed:
out(a) = out; %reorders the elements of out.
Of course, since you never check that all the elements of a are different, you may well end up with duplicated elements in your reordered structure (and others missing).
8 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!