MATLAB Answers

Kamel
0

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

Asked by Kamel
on 8 May 2019
Latest activity Answered by Matt J
on 10 May 2019
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

  0 Comments

Sign in to comment.

4 Answers

Answer by Adam Danz
on 8 May 2019
 Accepted Answer

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 Comments

thank you very much
Glad I could help!

Sign in to comment.


Answer by Geoff Hayes
on 8 May 2019

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 Comments

Nice! Simultaneous solutions with the same approach!
ok, thank you

Sign in to comment.


Answer by Jan
on 10 May 2019
Edited by Jan
on 10 May 2019

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

  0 Comments

Sign in to comment.


Answer by Matt J
on 10 May 2019

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

  0 Comments

Sign in to comment.