How can I fix my for loop to iterate diagonally?
24 次查看(过去 30 天)
显示 更早的评论
Hello all, I am extremely new to matlab and would like to know if anyone can help me fix/clarify my code.
I am trying to built a matrix of zeros with the A1 and A2 variables, so it can be any size, and then use a for loop to read a variable across the left diagonal, with indexes (1,1), (2,2), (3,3). For now, I have put it in manually at (1,1), but I would like to be able to fix this, as it won't work. Here is my code currently. I tried a for loop to basically say if (1,1) , (2,2) then it is a value of 6, but cannot understand. Any help is appreciated!
A1=2;
A2=2;
band=1;
e=1;
eps=2;
epss=3;
t=4;
tp=5;
M = zeros((A1*A2)*2*band,(N1*N2)*2*band)
M(1,1)=6
% left diagonal (1,1),(2,2),(3,3).....
for ii=1:(A1*A2)*2*band
for jj=1:(A1*A2)*2*band
if ii==jj
M(ii,jj)=6;
end
end
end
5 个评论
Voss
2021-12-26
@Karen Smith To do the other diagonal:
N = (A1*A2)*2*band;
for ii = 1:N
M(ii,N-ii+1) = 8; % set element (ii,N-ii+1) to 8 or whatever
end
N = (A1*A2)*2*band;
M(N:(N-1):numel(M)) = 8;
Both of those will set the "other" diagonal elements of an existing matrix M of size N-by-N.
If instead you want to create a new matrix with the "other" diagonal elements equal to some value and all other elements equal to zero, you can use @Stephen's first suggestion (use the diag() function) and flip() the result:
N = (A1*A2)*2*band;
M = flip(diag(8*ones(1,N)));
回答(1 个)
Voss
2021-12-18
Assuming that N1 and N2 in the code should be A1 and A2 (so that M is a square matrix), the easiest way to set the values along the diagonal to be [1 2 3 ...] might be:
A1=2;
A2=2;
band=1;
n = (A1*A2)*2*band;
M = zeros(n);
for ii = 1:n
M(ii,ii) = ii;
end
display(M);
Or to set all the diagonal elements to be 6:
A1=2;
A2=2;
band=1;
n = (A1*A2)*2*band;
M = zeros(n);
for ii = 1:n
M(ii,ii) = 6;
end
display(M);
% An alternative:
M = 6*eye(n);
display(M);
In general, to create a square matrix of zeros and set the diagonal elements to some values vals, you can do this kind of thing:
vals = [90 91 92 93 94 95 96 97];
A1=2;
A2=2;
band=1;
n = (A1*A2)*2*band;
M = zeros(n);
for ii = 1:n
M(ii,ii) = vals(ii);
end
display(M);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!