How can I create a 2-term, 1-by-1 string using sprintf?

조회 수: 14 (최근 30일)
Yasmin Ben Azouz
Yasmin Ben Azouz 2022년 5월 5일
댓글: Yasmin Ben Azouz 2022년 5월 9일
I am using the following code to refer to 4000x15 doubles I have in my workspace, they are named P1-17. When I use the code however, the name becomes a 1x2 char and therefore a variable itself. When I try to use it in the function that's in the loop, it does not refer to the 4000x15 data at all.
Does anyone know how to fix this or do it in another way? I have tried a lot of things but I can't figure this one out.
for j = 1:1:17
filename = (sprintf('%s%d','P',j)) ;
[sgmean] = DataPrep(filename) ;
end
  댓글 수: 3
Stephen23
Stephen23 2022년 5월 9일
"but use one of the alternatives in the documentation you attached?"
You don't need to guess, I already told you which alternative to use: LOAD into an output variable.
Yasmin Ben Azouz
Yasmin Ben Azouz 2022년 5월 9일
@Stephen23 Thank you so much! I am now loading the files into a struct using the code below, but the dimensions of the struct are not cooperating. After one run I get the error 'Subscripted assignment between dissimilar structures.', because only one field is created within a 17x1 struct. I want 17 fields in a 1x1 struct.. Do you have an idea on what I'm doing wrong now??
parts = {'P1.mat', 'P2.mat', 'P3.mat', 'P4.mat', 'P5.mat', 'P6.mat', 'P7.mat', 'P8.mat', 'P9.mat', 'P10.mat', 'P11.mat', 'P12.mat', 'P13.mat', 'P14.mat', 'P15.mat', 'P16.mat', 'P17.mat'} ;
for m = numel(parts):-1:1
S(m,1) = load(parts{m}) ;
end

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

채택된 답변

Stephen23
Stephen23 2022년 5월 9일
편집: Stephen23 2022년 5월 9일
Here is a way to import those badly-named variables, assuming exactly one variable per MAT file:
N = 17;
C = cell(1,N);
for kk = 1:N
F = sprintf('P%d',kk);
C(kk) = struct2cell(load(F));
end
Your data are stored in the cell array C, for example the 2nd file:
C{2}
The code would be simpler and more robust if the variable names were exactly the same in every file.
  댓글 수: 1
Yasmin Ben Azouz
Yasmin Ben Azouz 2022년 5월 9일
@Stephen23 Haha thankyou, this works. I will change my variable names I promise.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by