modify the matrix, rearrangement of elements

1 view (last 30 days)
I have a matrix a = [2 4 7 11; 7 9 5 54; 2 5 7 9; 12 41 45 21];
How to get the row matrix such that the elements of matrix a are arranged digonally upwards from the left .
For exapmle the row matrix should me [2 7 4 2 9 7 12 5 7 11 41 7 54 45 9 21];
Thanks in advance.
  2 Comments
Stephen23
Stephen23 on 27 May 2020
Edited: Stephen23 on 28 May 2020
a =
2 4 7 11
7 9 5 54
2 5 7 9
12 41 45 21
The main anti-diagonal has values [12,5,5,11] (from bottom left to top right), but your example output shows the values [...,12,5,7,11,...]: please clarify the correct expected values.
CHANDRABHAN Singh
CHANDRABHAN Singh on 28 May 2020
sir, it is ...12, 5, 5,11..... It is a typing mistake. Sorry for this.

Sign in to comment.

Accepted Answer

Srivardhan Gadila
Srivardhan Gadila on 27 May 2020
The following code might help you:
sz = size(a);
rowMat = zeros(1,prod(sz));
ind = 1;
for i = 1:sz(1)
j = 1;
ii = i;
while ii>0 && j<=i
rowMat(ind) = a(ii,j);
ind = ind+1;
j = j+1;
ii = ii-1;
end
if i == sz(1)
for j = 2:sz(2)
ii = i;
jj = j;
while ii>1 && jj<=i
rowMat(ind) = a(ii,jj);
ind = ind+1;
jj = jj+1;
ii = ii-1;
end
end
end
end
a
rowMat
Refer to MATLAB Onramp to get started with MATLAB.

More Answers (1)

Stephen23
Stephen23 on 27 May 2020
Edited: Stephen23 on 27 May 2020
>> a = [2,4,7,11;7,9,5,54;2,5,7,9;12,41,45,21]
a =
2 4 7 11
7 9 5 54
2 5 7 9
12 41 45 21
>> S = size(a);
>> V = 1-S(1):S(2)-1;
>> F = @(d)diag(flipud(a),d);
>> b = cell2mat(arrayfun(F,V(:),'uni',0)).'
b =
2 7 4 2 9 7 12 5 5 11 41 7 54 45 9 21

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!