How can I implement different structs in a cell

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.
Thank you for the quick input, I will take a look at implementing non-scalar structure to the code.

Sign in to comment.

 Accepted Answer

Simple:
dataset = rand(3);
N = 5;
signal = cell(1,N);
for k = 1:N
signal{k} = dataset;
end

2 Comments

This is definitely preferable. My suggestion attempted to follow what you were aiming for more closely but is not something I would ever do. Using the array index as your key into the respective data rather than a different field name is far superior.
By avoiding dynamic strings this code works just fine! Thank you

Sign in to comment.

More Answers (1)

Adam
Adam on 25 Oct 2016
Edited: Adam on 25 Oct 2016
signal(i).( ['SIGNAL' num2str(i)] ) = dataset;
'dataset' is a type in Matlab though so not advisable as the name of a variable.

Tags

Community Treasure Hunt

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

Start Hunting!