How can I implement different structs in a cell
Show older comments
I am trying to implement multiple structs in a cell array but can't really get my head around it.
example:
N = 3;
signal = cell(N,1)
dataset = rand(3);
for i = 1:N
signal{i,1} = ['SIGNAL' num2str(k)]
end
This returns a 3x1 cell 'signal' with the following contents:
SIGNAL1
SIGNAL2
SIGNAL3
I would like the SIGNAL1-3 to contain the data "dataset". How can this be implemented?
I have tried the following:
N = 3;
signal = cell(N,1)
dataset = rand(3);
for i = 1:N
eval(['SIGNAL' num2str(i) '=dataset'])
end
This is bad programming using eval as far as I have read on different forums. But it was able to make a Struct with the data inside, but I would like to add the struct SIGNAL1, SIGNAL2, etc in my cell array signal. (NB: my dataset in real life generates a struct with different elements in a signal, due to it's a file loaded I can't implement it in this post).
2 Comments
Using eval is an awful solution for such trivial code:
A much better solution for you would be to use a non-scalar structure rather than lots of structures in a cell array, or simply use indexing.
Your concept of putting meta-data into your variable names and fieldnames will also make your code more complicated and your life harder. Good data design makes the code simpler and more reliable. Read this discussion for an explanation of why it is a poor practice to put data and meta-data in variable names or fieldnames:
Just use indexing. You will not regret learning how to use indexing effectively.
Daniel Eidsvåg
on 26 Oct 2016
Accepted Answer
More Answers (1)
signal(i).( ['SIGNAL' num2str(i)] ) = dataset;
'dataset' is a type in Matlab though so not advisable as the name of a variable.
Categories
Find more on Tuning Goals 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!