필터 지우기
필터 지우기

Loading and naming specific columns

조회 수: 1 (최근 30일)
Anna
Anna 2011년 8월 30일
Hello,
I used this code to import and name data in Matlab:
for i=1951:2000
fileName=['arunoff_' num2str(i)];
dataStruct.(fileName)=importdata([fileName '.txt']);
end
This creates data structure dataStruct.arunoff_(i).data for each year (1951-2000). Next I would like to create and name another set of variables using the third column in 'data' (i.e. dataStruct.arunoff_1951.data(:,3), dataStruct.arunoff_1952.data(:,3) etc.). However, I don't know how to write a loop that does that and was wondering if someone could help me with this? My main problem is I don't know how to tell the loop to use data in each a_runoff(i) structure.
Hope this makes sense, thanks very much for the help!

채택된 답변

Walter Roberson
Walter Roberson 2011년 8월 30일
fn = fieldnames(dataStruct);
for K = 1:length(fn)
newStruct.([fn 'd3']) = dataStruct.(fn).data(:,3);
end
  댓글 수: 2
Andrei Bobrov
Andrei Bobrov 2011년 8월 30일
Hi Walter!
Little typo.
for K = 1:length(fn)
newStruct.([fn{K} 'd3']) = dataStruct.(fn{K}).data(:,3);
end
Walter Roberson
Walter Roberson 2011년 8월 30일
Good point. I mentally started with K = fn (i.e., iterate over the cells) and didn't clean up properly afterwards.

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

추가 답변 (1개)

Anna
Anna 2011년 8월 30일
Thank you for your replies Walter and Andrei!
I used the code you supplied and it worked very well. I now have another problem though that I would really appreciate help with. I want to calculate the mean of all the values in each field in 'newStruct'. The values are arranged as one column in each field.
This is the code I tried using:
fn = fieldnames(newStruct); for K = 1:length(fn) Mean.(fn{K}) = mean(newStruct.(fn{K})); end
but I get this error: 'Subscript indices must either be real positive integers or logical'.
Anything you could suggest?

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by