how to full fill the diagonal of a matrix by a vector

조회 수: 8 (최근 30일)
Kamel
Kamel 2019년 5월 8일
답변: Matt J 2019년 5월 10일
hello
how can i full fill a matrix (17*9) by a vector by length 9
for example i have the vector d=[1 2 3 ] and the matrix zeros(5*5) and i want to make the output matrix like this
1 0 0 3 2
2 1 0 0 3
3 2 1 0 0
0 3 2 1 0
0 0 3 2 1
thanks

채택된 답변

Adam Danz
Adam Danz 2019년 5월 8일
This approach uses circshift() to circularly shift the columns of matrix.
m = zeros(5,5);
v = [1,2,3];
% Loop through each column of m
for i = 1:size(m,2)
m(1:length(v),i) = v;
m(:,i) = circshift(m(:,1), i-1);
end
Result:
m =
1 0 0 3 2
2 1 0 0 3
3 2 1 0 0
0 3 2 1 0
0 0 3 2 1
  댓글 수: 2
Kamel
Kamel 2019년 5월 8일
thank you very much
Adam Danz
Adam Danz 2019년 5월 10일
Glad I could help!

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

추가 답변 (3개)

Geoff Hayes
Geoff Hayes 2019년 5월 8일
Ahmed - try using
a = [1 2 3 0 0]';
A = cell2mat(arrayfun(@(x)circshift(a,x-1),1:length(a), 'UniformOutput', false));
We use arrayfun and circshift to apply an anonymous function that shifts the a down by one element (less one) for each of the five columns in your output matrix. We use cell2mat to conver the cell array output to a matrix.
  댓글 수: 2
Adam Danz
Adam Danz 2019년 5월 8일
Nice! Simultaneous solutions with the same approach!
Kamel
Kamel 2019년 5월 8일
편집: Kamel 2019년 5월 8일
ok, thank you

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


Jan
Jan 2019년 5월 10일
편집: Jan 2019년 5월 10일
m = zeros(5,5);
v = [1,2,3,4];
n = numel(v);
index = 1:n;
for i = 1:size(m,2)
m(mod(i-1:i+n-2, 5)+1, i) = v;
end

Matt J
Matt J 2019년 5월 10일
>> full(interpMatrix([1,2,3],1,5,1,'circ'))
ans =
1 0 0 3 2
2 1 0 0 3
3 2 1 0 0
0 3 2 1 0
0 0 3 2 1

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by