필터 지우기
필터 지우기

Using the struct function with a for loop

조회 수: 1 (최근 30일)
Meghan
Meghan 2016년 8월 25일
편집: Stephen23 2016년 8월 25일
Hello
I have a matrix that is 89x4. I've used a for loop to extract each row of data to make 89 new matrices. I needed to do that because each row is a new nodal point in my data set. What I need to do now is make a structure array with a list of each nodal point.
My original for loop is
for n=1:89;
eval(['Node_' num2str(n) '=nodeXYZ(n,:);']);
end
That gives me each matrix (Node_1 to Node_89). I've tried to used dynamics naming within a for loop to make a different array within a structure for each node but I keep getting errors. Or when it works its completely wrong.
Triangle_points.node_data.nodes=struct('Node',Node_1);
for field='Node';
Triangle_points.node_data.nodes.(field)=Node_1;
end
That is along the lines of what I'm trying. Its probably very wrong, which is why I need the help. I really don't want to have to write out 89 different fields and values! Any suggestions or help on this would be appreciated.
  댓글 수: 1
Stephen23
Stephen23 2016년 8월 25일
편집: Stephen23 2016년 8월 25일
@Meghan: using eval is a buggy, slow, and obfuscated way to write code. Learn to code without it and your code will be faster, better, neater, and easier to read. There are so many tools that help you when you do not use eval, such as code hinting, tab completion, variable highlighting, help, syntax error highlighting, etc, etc,, which help you to write good code none of them work when you use eval! Summary: learn to write code without eval.

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

채택된 답변

Adam
Adam 2016년 8월 25일
편집: Adam 2016년 8월 25일
Something like
for n = 1:89
fieldName = strcat( 'Node_', num2str( n ) );
Triangle_points.node_data.nodes.( fieldName ) = nodeXYZ(n,:);
end
should give you the output you are looking for without needing to go via 89 unwanted variables. I would question why you would want this setup though.
You could instead use an array of 89 structures, each just with a 'node' field or simply keep your data in its original array as the best option. Most maths that you would want to do can be done on data that just sits in a single neat multi-dimensional numeric array. Moving away from one numeric array into 89 of them or a struct with 89 fields or 89 structs with 1 field all just make subsequent operations all the more complicated and inefficient.
  댓글 수: 1
Meghan
Meghan 2016년 8월 25일
Thank you :) that worked. I would rather not separate the data this way either but I've been asked to do it. It feeds into a model which run in Java so I think he wants it this way for that reason, not too sure!

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

추가 답변 (1개)

Azzi Abdelmalek
Azzi Abdelmalek 2016년 8월 25일

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by