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

Stephen23
Stephen23 2016년 10월 25일
편집: Stephen23 2016년 10월 25일
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.

댓글을 달려면 로그인하십시오.

 채택된 답변

Stephen23
Stephen23 2016년 10월 25일

0 개 추천

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

댓글 수: 2

Adam
Adam 2016년 10월 26일
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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Adam
Adam 2016년 10월 25일
편집: Adam 2016년 10월 25일

0 개 추천

signal(i).( ['SIGNAL' num2str(i)] ) = dataset;
'dataset' is a type in Matlab though so not advisable as the name of a variable.

태그

질문:

2016년 10월 25일

댓글:

2016년 10월 26일

Community Treasure Hunt

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

Start Hunting!

Translated by