MATLAB: How to create a structure with a loop

loopstructure

Hi,
It has been hours that I'm struggling and still …no way to solve it. I guess I just need a quick tip!
I want to create a new structure, based on some already existing structures called "Measurement1", "Measurement2" ects… (size : 1×1). But I would like to do it in a smart way by using a loop. It works when I assigned each of them directly, but as soon as it's about a loop, it generates the error "Index exceeds matrix dimensions."
You will find below my code where each value is assigned arbitrary, just in order to give you an idea of what I'm looking for. Instead of having "1","2", I would like to index it.
MeasurementNumber = 'MeasurementData';
Pressure = 'Pressure';
Frequency = 'Frequency';
Absorbance = 'Absorbance';
value = {Measurement1;
Measurement2;}
value2 = {Measurement1.PRESSURE;
Measurement2.PRESSURE;}
value3 = {Measurement1.FREQ;
Measurement2.FREQ;}
value4 = {Measurement1.ABSORBANCE;
Measurement2.ABSORBANCE;}
Structure = struct(MeasurementNumber,value,Pressure,value2,Frequency,value3,Absorbance,value4)
I got the error when I run this one :
for i=1:nFile;
value = {Measurement(i)};
end
Thank you for your precious help ! (Sorry for potential English mistakes, I'm not a native speaker !)

Best Answer

Non-scalar Structure: I do not really follow your example, but perhaps the best solution wold be to use a non-scalar structure, which are very simple and allow you to use indexing in a loop:
S(1).data = 1:3;
S(1).name = 'Anna';
S(2).data = 4:6;
S(2).name = 'Bob';
S(3).data = 7:9;
S(3).name = 'Cat';
Acessing this non-scalar structure is very simple, you can loop over its elements:
for k = 1:numel(S)
S(k).name
end
which prints
ans =
Anna
ans =
Bob
ans =
Cat
or generate a comma separated list and concatenate these into arrays for doing your work:
>> mat = vertcat(S.data)
mat =
1 2 3
4 5 6
7 8 9
>> names = {S.name}
names =
'Anna' 'Bob' 'Cat'
Avoid Numbered Variables! Whatever you do, do not put lots of numbered variables into your workspace! Note that if each variable has a number then this is a de-facto index: so why not turn into into a real index (of one variable), which would allow you to use fast and efficient indexing?
Instead of this (slow and buggy to access)
var1 = ...
var2 = ...
var3 = ...
this is much better:
var(1) = ...
var(2) = ...
var(3) = ...
No workspace clutter, much faster, less buggy, easier to read, easier to bug fix, lets you use the inbuilt Editor mlint and code-helper tools...
Related Question