Adding a row and column is a matrix
이전 댓글 표시
I intializes a zero matrix [#bus,#bus] (name it z). And would like to increase a row and a column and do that in a for loop (name it zmod).
Moreover, the new row should be equal to the transposed of the new column.
How can I do this?
답변 (1개)
William Rose
2021년 3월 29일
This code creates a square array of zeros. Then it adds a row and a column which are transpose of eachother, in a for loop, until it reaches the FinalSize.
%augmentArray.m
%WCRose 20210329
clear;
InitSize=3;
FinalSize=5;
z=zeros(InitSize);
zmod=z;
for i=InitSize:FinalSize-1
a=rand(i,1); %column to add
b=[a',rand(1)]; %row to add
zmod=[zmod,a;b];
end
disp(zmod)
Try it.
댓글 수: 4
Fatima Yusuf
2021년 3월 29일
William Rose
2021년 3월 29일
rand(i,1) generates an array of random numbers, with i rows and 1 column. rand(1) generates a single random number. I used rand to generate some numbers, so that you could tell, in the results, that The dded rows were the transpose of the added columns. If I had just added zeros or ones to th array, you might have doubted that the rows and columns were really transpose of each other.
Fatima Yusuf
2021년 3월 30일
William Rose
2021년 3월 30일
Then you could change the for loop to the following:
for i=InitSize:FinalSize-1
a=zeros(i,1); %column to add
b=zeros(1,i+1); %row to add
zmod=[zmod,a;b];
end
or you could do
for i=InitSize:FinalSize-1
zmod=[zmod,zeros(i,1);zeros(1,i+1)];
end
If that is what you want to do, then the script above seems unnecessary. You could replace the whole script with the line
zmod=zeros(FinalSize);
which produces the same result as the for loop.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!