ben
ben

Reputation: 799

How to change name of matrix receiving data on each loop

In MATLAB, I am given a cell array M with lots of good stuff I need to put into many differently named matrices. I need to do this sort of thing:

matrix_name_list={'name1' 'name2' 'name3'};
lasti=length(matrix_name_list);
for i=1:lasti
    matrix_name=matrix_name_list{i};
    matrix_name=M{i};
end

I.e. I need to change the name of the matrix that is receiving the data in each loop. Any way I can do this?

Upvotes: 0

Views: 2262

Answers (3)

grantnz
grantnz

Reputation: 7423

assignin is the way to do this.

matrix_name_list={'name1' 'name2' 'name3'};
lasti=length(matrix_name_list);
for i=1:lasti
    matrix_name=matrix_name_list{i};
    assignin('caller',matrix_name,M{i});
end

Upvotes: 0

shoelzer
shoelzer

Reputation: 10708

If your data is the same size on each iteration, you are probably better off having one big matrix with an extra dimension. It's much easier than dealing with lots of matrices with slightly different names. Try something like this:

n = length(M);
matrix = zeros(length(M{i}), n);
for i = 1:n
    matrix(:,i) = M{i};
end

% now get data for iteration 4
matrix(:,4)

If you really need separate matrices, one option is to make a struct with dynamic fieldnames. Example:

matrix_name_list={'name1' 'name2' 'name3'};
lasti = length(matrix_name_list);
for i = 1:lasti
    data.(matrix_name_list{i}) = M{i};
end

Upvotes: 2

Steve
Steve

Reputation: 4097

This is not my favorite thing to do. Better to go with a cell array or multidimensional array as people have suggested. However, you can do this if you really are set on it:

M = {1, 2, 3};
matrix_name_list={'name1' 'name2' 'name3'};
lasti=length(matrix_name_list);
for i=1:lasti
    eval([matrix_name_list{i} '=M{i}']);
end

Upvotes: 1

Related Questions