Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to save in Matlab some matrices created at each iteration of a loop using names depending on the loop index h. More precisely, the code is

for h=1:4

   A=randn(2,1);
   B=randn(2,1);
   C=randn(2,1);

save(sprintf('data%d.mat',h),'-v7.3', 'A' , 'B', 'C')

end

for h=3, I get the matrix data3, whose name depends on the loop index, containing the matrices A,B,C. I want to modify that line of code in a way such that data3 containes A3,B3,C3.

Note: using save(sprintf('data%d.mat',h), ['A' h], ['B' h], ['C' h] ,'-v7.3') gives the error

Error using save
'A' is not a valid variable name.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
166 views
Welcome To Ask or Share your Answers For Others

1 Answer

I wonder if you have used the correct signature for save method.

The correct signature for your job is:

save (filename, version, variables).

as opposed to save(filename, variables, version). But because -v is parsed properly, it is okay.

You can check if it is a valid variable name by using isvarname(string)

This should do it:

  save(sprintf('data%d.mat',h), ['A' h], ['B' h], ['C' h] ,'-v7.3')

It would be better if you AVOIDED the -v7.3 as you are probably hardcoding the version-related settings for the MAT files. Try and use without the -v argument.

BUT your matrices are A, B, and C as opposed to A1, B1, C1,....etc. You can supply whatever variable name you like in save method, AS LONG AS THEY EXIST in your current workspace.

All you needed is a string concatenation which, in MATLAB, is similar to declaring a matrix e.g. a = ['my' 'name' 'is' 'Bolshoi']


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...