Navigating a Structure Using Cell Arrays in a For Loop

I'm using a full Academic Suite MATLAB version 2018a.
Why does the following work:
scan1 = 'scan398';
plot1 = 'Item1';
ext = 'units'
figure 1
surface(a.(scan1).rel_X, a.(scan1).rel_Y, a.(scan1).(plot1).(ext), 'LineStyle', 'none')
%graph settings here%
but below produces the error: Argument to dynamic structure reference must evaluate to a valid field name.
scans = {'scan398', 'scan405', 'scan439'}
plot = {'Item1' , 'Item2' , 'Item3'}
ext = 'units'
for j = 1:length(scans)
frma(j) = scans(j)
for i = 1:length(plot)
figure
surface(a.(frma(j)).rel_X, a.(frma(j)).rel_Y, a.(frma(j)).(plot(i)).(ext), 'LineStyle', 'none')
%graph settings here%
end
end
I entered a breakpoint to see what the 'frma' cell array looks like:
frma =
1×1 cell array
{'scan398'}
What's inside the surface function?
a.'scan398'.'Item1'
%or
a.scan398.Item1
It should be working if it's the second case. If it's the first, how do I fix it?

 Risposta accettata

Stephen23
Stephen23 il 22 Mag 2018
Modificato: Stephen23 il 22 Mag 2018
You are using the wrong brackets: you need to use {} to get data out of a cell array, e.g.:
surface(a.(scans{j}).rel_X, ...)
Accessing data in cell arrays is really very simple:
  • () parentheses refer to the cells themselves.
  • {} curly braces refer to the cell contents.
You can read more about indexing cell arrays in the documentation:
See also:
In your code you use indexing and parentheses to get one single cell and then try to use this as the fieldnames... but clearly using a scalar cell for a fieldname is an error. For the fieldname you need to provide a char vector. The char vector you want is contained within the cell, so you need to use curly braces to get it out of the cell. Just like you would use to put data into the cell array.

Più risposte (0)

Categorie

Scopri di più su Creating, Deleting, and Querying Graphics Objects in Centro assistenza e File Exchange

Prodotti

Release

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by