Star
Star

Reputation: 2299

Calling and working with variables in a loop in Matlab whose names depend on the loop index?

I need to work with variables at each iteration of a loop in Matlab whose names depend on the loop index h (e.g. if h=1 I want to use data1 e to create other variables). Is there a way to do it? I cannot use cells, because the variables are very large matrices and I have memory problems using cells.

Example:

data1=[1,2,3];
data2=[4,5,6];
data3=[7,8,9];  %they are in the workspace

for h=1:3
    % A`h'=data`h'+6
    % save A`h'
end

Upvotes: 0

Views: 242

Answers (2)

laureapresa
laureapresa

Reputation: 179

As far as I understand, you either want to make a matrix:

 A = [1 2 3;
      4 5 6;
      7 8 9];

or a vector:

A =[1; 2; 3; 4; 5; 6; 7; 8; 9];

In the first case, just writing

A = [data1;data2;data3];

should do the trick. Otherwise, look into horzcat for a horizontal vector and vertcat for a vertical one:

A = horzcat(data1,data2,data3);
A = vertcat(data1',data2',data3');

Upvotes: -1

Shai
Shai

Reputation: 114786

I think you should consider using structure with dynamic field names (see more details here).
For example

 for h=1:n
     dataName = sprintf('data%d', h); %// dynamic name
     resultName = sprintf('res%d', h); %// dynamic name
     base.(resName) = myFunction( base.(currentName) ); %// process data and save to result
 end

The nice thing about this approach (especially if you run into memory problems) is that save and load supports this approach:

 for h=1:n
     dataName = sprintf('data%d', h); %// dynamic name

     base = load( 'myHugeMatFile.mat', dataName ); %// loads only one variable from the file
     %// now the variable is a field in base 

     resultName = sprintf('res%d', h); %// dynamic name

     base.(resName) = myFunction( base.(currentName) ); %// process data and save to result

     save( 'myResultsFile.mat', '-struct', '-append', 'base' ); %// please verify this works - I'm not 100% certain here.
 end

Note how save and load can tread struct fields as different variables when needed.

Upvotes: 3

Related Questions