MATLAB Answers

Write a MATLAB algorithm takes as input the vector x and computes C rowwise

3 views (last 30 days)
Pascale Bou Chahine
Pascale Bou Chahine on 18 Sep 2020
Commented: KSSV on 19 Sep 2020
Say I have a vector x in R^3, such that x = [1 2 3]. I want to form from x, a matrix C = [1 2 3; 3 1 2; 2 3 1]. So, basically, the pattern here is that the first row of C is the vector itself, then the last entry of the first row is the first entry of the second row and the numbers (1 and 2) get shifted, and then the last entry of the second row is the first entry of the third row and the numbers (3 and 1) get shifted.
I want to write a general algorithm for any vector x in R^n, so this is what I have written:
function [C] = rowwise(x)
n = length(x);
C(1,:) = x;
for i = 2:n
for j = 1:n
C(i,j) = C(i-1,"?");
end
end
I don't know what to put instead of the question mark. And is my algorithm correct? Any other ways, please? And how to compute that same matrix C but columnwise? Thank you

  0 Comments

Sign in to comment.

Answers (1)

KSSV
KSSV on 18 Sep 2020
Read about circshift.

  4 Comments

Show 1 older comment
KSSV
KSSV on 19 Sep 2020
C = [1 2 3] ;
n = length(C) ;
iwant = zeros(n) ;
iwant(1,:) = C ;
for i = 2:n
iwant(i,:) = circshift(iwant(i-1,:),1) ;
end
Pascale Bou Chahine
Pascale Bou Chahine on 19 Sep 2020
And how to write an algorithm to get the same matrix C, but columnwise and not rowwise?

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by