I need to create a matrix with for loop.

조회 수: 2 (최근 30일)
sermet
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)]
thanks in advance.

채택된 답변

Guillaume
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
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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by