Problem of inserting values into array within a for loop
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Has anyone else met with the problem of MATLAB not liking to assign values to matrix in a for loop? E.g.
for i = 1:14
targetLabel = BLOB_STATS(i,1);
blob = (bm == targetLabel);
perimeterLength = regionprops(blob, 'Perimeter');
BLOB_STATS(i,3) = perimeterLength;
end
But if I use fixed coordinates, e.g. BLOB_STATS(1,3) = perimeterLength; it works fine.
The error I get says: "The following error occurred converting from struct to double: Error using double Conversion to double from struct is not possible."
0 Kommentare
Akzeptierte Antwort
Sven
am 12 Apr. 2014
Bearbeitet: Sven
am 12 Apr. 2014
Hi Kornelia,
This one has a straight forward answer.
perimeterLength = regionprops(blob, 'Perimeter');
will always return a structure as the contents of perimeterLength. You can check this out yourself by just inspecting the contents of perimeterLength before you assign it, and notice that the value you're looking for is actually stored in:
perimeterLength.Perimeter
So I'll bet that changing your code to:
BLOB_STATS(i,3) = perimeterLength.Perimeter;
will make things work again (except for one particular case I'll describe below).
The reason why the line
BLOB_STATS(i,3) = perimeterLength;
worked fine was that you would have to have called this before you filled BLOB_STATS with any numeric contents. Structure arrays exist, so it's perfectly legal to insert a structure into, say, the 5th element of a variable that doesn't exist:
newVar(5) = struct('Perimeter', 1234) % no error
But it's not ok to try to put the same thing into an already-defined matrix:
newVar = ones(10,1);
newVar(5) = struct('Perimeter',1234) % same error that you got
Now, back with your loop... just be careful of what could happen if your blob variable is all zeros. In that situation, regionprops will return an empty structure, so the contents of the 'Perimeter' field will be empty. It's not legal to run the following bit of code, so just be careful to ensure there will always be something for regionprops to return:
newVar = ones(4,3)
newVar(2,2) = [] % you cannot assign an empty matrix to an array element
Did this clear things up for you?
1 Kommentar
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Characters and Strings 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!