MATLAB: Strings and access to matrix elements

MATLABmatricesstrings

I used the following piece of Matlab code to generate a set of matrices D1_1,…,D1_5:
x=-1:0.01:1;
for i=1:5
eval(['D1_' num2str(i) '=zeros(1,numel(x));'])
end
what shall I do if I now want to assign the value 1 to the i-th value of each matrix? In other words, I'd like to write something like
for i=1:5
D1_i(1,i)=1;
end
but I don't understand which is the right way to do it. I would like to end up with
D1_1(1,1)=1 , D1_2(1,2)=1 , D1_3(1,3)=1 , D1_4(1,4)=1 , D1_5(1,5)=1
Thanks in advance 🙂

Best Answer

Ah, we were all inefficient coders at one point. Here's how to implement what the rest are suggesting:
x = -1:0.01:1;
D = repmat({zeros(1, numel(x))}, 1, 5); %Create 1x5 cell that stores zero vectors
for j = 1:length(D)
D{1, j}(1, 2) = 1; %See how this is much better than eval(['D1_' num2str(i) '(1, 2) = 1']);
end
To access your "D1_1" at position (1, 2):
D{1, 1}(1, 2) %Returns 1