필터 지우기
필터 지우기

Assgin a name to sequentially imported files

조회 수: 2 (최근 30일)
Tala Hed
Tala Hed 2018년 2월 25일
편집: per isakson 2018년 2월 25일
Experts,
I have imported 8 files sequentially using this piece of code
for i=1:8
fileName=['data' num2str(i)];
dataStruct.(fileName)=load([fileName '.csv']);
end
Now I want to assign a variable to the first imported file, do some operations on it and then save the results. Then, assign the second imported file to the same variable and do the same operations. Then the third one and so on. How can I do that? I mention the WRONG way that I used to be clear below:
for k=1:8
M5=dataStruct.data(k);
[I,J]=size(M5);
BLAH...BLA... BLAH
end
Which results in this error {{{Reference to non-existent field 'data'.}}} Can you please help me? I do appreciate your attention
  댓글 수: 1
Stephen23
Stephen23 2018년 2월 25일
편집: Stephen23 2018년 2월 25일
The cause of the error is quite straightforward: you define each fieldname like this:
['data' num2str(i)]
giving filenames data1, data2, etc. And then you try to access the field data, which does not exist, thus the error. Note that indexing into that field data(k) is totally unrelated to the fieldname.

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

채택된 답변

Stephen23
Stephen23 2018년 2월 25일
편집: Stephen23 2018년 2월 25일
I don't see any reason why you need to use a structure: it just makes accessing the data more complex for you and serves no obvious purpose. A cell array would be much simpler:
N = 8;
C = cell(1,N);
for k = 1:N
fileName = sprintf('data%d.csv',k);
C{k} = load(fileName,'-ascii');
end
And then accessing the data in the cell array is trivial with just indexing:
for k = 1:numel(C)
M = C{k};
...
end
If you really want to use a structure then you could use a non-scalar structure:
N = 8;
S = struct('data',cell(1,N));
for k = 1:8
fileName = sprintf('data%d.csv',k);
S(k).data = load(fileName,'-ascii');
end
and then simply
for k = 1:numel(S)
M = S(k).data;
...
end

추가 답변 (2개)

Image Analyst
Image Analyst 2018년 2월 25일

per isakson
per isakson 2018년 2월 25일
편집: per isakson 2018년 2월 25일
Given dataStruct. An alternative approach
results = structfun( @do_some_operations_on, dataStruct, 'uni',false );
where
function out = do_some_operations_on( data )
BLAH ... BLA... BLAH
end

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by