# I need to create a matrix with for loop.

조회 수: 2(최근 30일)
sermet 2014년 11월 27일
답변: Govind Narayan Sahu 2018년 7월 6일
x=[100;120;130;140;150];
y=[120;130;140;150;170];
z=[130;150;170;180;190];
%I need to create this matrix with loop because the number of the rows can be changed;
A=[x(1) y(1) z(1) 0 0 0 0 0 0;0 0 0 x(1) y(1) z(1) 0 0 0;0 0 0 0 0 0 x(1) y(1) z(1);x(2) y(2) z(2) 0 0 0 0 0 0;0 0 0 x(2) y(2) z(2) 0 0 0;...
0 0 0 0 0 0 x(2) y(2) z(2);x(3) y(3) z(3) 0 0 0 0 0 0;0 0 0 x(3) y(3) z(3) 0 0 0;0 0 0 0 0 0 x(3) y(3) z(3);x(4) y(4) z(4) 0 0 0 0 0 0;...
0 0 0 x(4) y(4) z(4) 0 0 0;0 0 0 0 0 0 x(4) y(4) z(4);x(5) y(5) z(5) 0 0 0 0 0 0;0 0 0 x(5) y(5) z(5) 0 0 0;0 0 0 0 0 0 x(5) y(5) z(5)]

댓글을 달려면 로그인하십시오.

### 채택된 답변

Guillaume 2014년 11월 27일
xyz = [x y z];
A = cellfun(@(row) blkdiag(row, row, row), num2cell(xyz, 2), 'UniformOutput', false);
A = vertcat(A{:})
You can always replace the cellfun by a for loop if you really want it.

댓글을 달려면 로그인하십시오.

### 추가 답변(1개)

Govind Narayan Sahu 2018년 7월 6일
clear;clc
n =1:1:3;
for i = 1:length(n)
A{i} = [n(i) 0;
0 2*n(i)]
AA = blkdiag(A{:})
end

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by