File names in plots legend, from struct data; Matlab says is not an array.

I have multiple files with struct data, and I want to place a legend with a group of data.
I tried to use the Benjamin Kraus to solve it, but the message of Matlab is: Cell contents assignment to a non-cell array object.
https://www.mathworks.com/matlabcentral/answers/81979-an-elegant-alternative-to-nested-for-loops-for-plotting-simulations The code which I wrote:
for i = 1:numreg
leg{i} = [BLR4.record{i}.name];
C1 = BLR4.record{i}.T;
C2 = BLR4.record{i}.Sd;
plot (C1,C2)
hold on
end
legend(leg)

1 Comment

[BLR4.record{i}.name]
If BLR4.record{i} is a scalar structure, then those square brackets are superfluous:
Note also that using a non-scalar structure might be better than a cell array of scalar structures:

Sign in to comment.

 Accepted Answer

Probably leg is not a cell array, so trying to use cell array indexing with it is going to be an error.
Solution: make leg a cell array:
leg = cell(1,numreg);
for ...
leg{k} = ...
...
end

8 Comments

Thanks you so much. The data in this file structure is in text form, I don't know if it is a problem. When I use your suggestion: Error using cell Size inputs must be scalar.
@Isai Fernandez: please upload your code by clicking the paperclip button. Also show us the complete error message. This means all of the red text.
I also asked for the complete error message. Here is that request again, in case you missed it:
Also show us the complete error message. This means all of the red text.
@Stephen This is the message:
Error using cell
Size inputs must be scalar.
Error in DynT3 (line 16)
leg = cell(1,numreg);
Then figure out why "numreg" is an array, cell, or table instead of a scalar (a single integer number).
whos numreg
If you want, you can come back here and tell us what the above line of code puts into the command window.
In your code you define numreg like this:
numreg = size(BLR4.record);
which means that numreg will be a numeric vector with atleast two elements (i.e. a vector). But to use cell (and colon reliably) you will need to use a scalar. Most likely you want the number of rows, so you can simply specify that you only want that single value (i.e. scalar) when you call size:
numreg = size(BLR4.record,1);
@Stephen Cobeldick Yeah. Thank you so much, that was it.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!