Question on creating dynamic matrix variables
45 views (last 30 days)
Show older comments
Tsz Tsun
on 12 Apr 2024 at 17:12
Commented: Tsz Tsun
on 12 Apr 2024 at 18:12
Hi all, I would like to know how to write dynamic matrix variables. For example, I have the following:
clear all;
n=11
for i=1:n-1
A1(i,i+1) = 1;
A1(i+1,i) = 1;
end
A1
for i=1:n-2
A2(i,i+2) = 1;
A2(i+2,i) = 1;
end
A2
for i=1:n-3
A3(i,i+3) = 1;
A3(i+3,i) = 1;
end
A3
And I would like to make something like this:
for k=1:1:3
for i=1:n-1
A[k](i,i+1) = 1;
A[k](i+1,i) = 1;
end
end
Or alternatively, is there a neat way to do so?
1 Comment
Accepted Answer
Stephen23
on 12 Apr 2024 at 17:23
Edited: Stephen23
on 12 Apr 2024 at 17:41
"Or alternatively, is there a neat way to do so?"
Of course there is: indexing. Either into a numeric array or into a container array (e.g. a cell array).
Indexing is neat, simple, and efficient. Unlike what you are trying to do.
n = 11; % size of each matrix
D = 2:4; % vector of indices of the 1's
C = cell(size(D));
for k = 1:numel(D)
V = zeros(1,n);
V(D(k)) = 1;
C{k} = toeplitz(V);
end
Checking:
C{1}
C{2}
C{3}
5 Comments
Stephen23
on 12 Apr 2024 at 18:09
Either modify the TOEPLITZ call with two vector inputs, or call DIAG:
n = 11; % size of each matrix
D = 1:3; % offset of the diagonal
C = cell(size(D));
for k = 1:numel(D)
C{k} = diag(ones(1,n-D(k)),D(k));
end
C{1}
C{2}
C{3}
More Answers (1)
Taylor
on 12 Apr 2024 at 17:27
May be worth looking into structures instead of matrices. https://www.mathworks.com/help/matlab/matlab_prog/generate-field-names-from-variables.html
0 Comments
See Also
Categories
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!