1D array values to 2D matrix

3 Ansichten (letzte 30 Tage)
Eduardo Santos
Eduardo Santos am 8 Apr. 2019
Kommentiert: Eduardo Santos am 4 Jan. 2021
I would like to 'convert' a 1D array to a 2D matrix considering the value inside the array as:
A =
1 3 5 4 3
B =
1 3 5 4 3
0 3 5 4 3
0 3 5 4 3
0 0 5 4 0
0 0 5 0 0
Can you suggest a fast way to do that?

Akzeptierte Antwort

Adam Danz
Adam Danz am 8 Apr. 2019
A for-loop would make a cleaner read (I could provide that upon request) but here's two lines the do the trick.
base = cellfun(@(x)repmat(x,x,1), num2cell(A), 'UniformOutput', false);
cell2mat(cellfun(@(y,n) padarray(y,n, 'post'),base, num2cell(max(A)-A), 'UniformOutput', false))
ans =
1 3 5 4 3
0 3 5 4 3
0 3 5 4 3
0 0 5 4 0
0 0 5 0 0
  6 Kommentare
Adam Danz
Adam Danz am 27 Dez. 2020
A = [1,3,5,4,3]
A = 1×5
1 3 5 4 3
B = zeros(max(A),numel(A));
for i = 1:numel(A)
B(1:A(i),i) = 1:A(i);
end
disp(B)
1 1 1 1 1 0 2 2 2 2 0 3 3 3 3 0 0 4 4 0 0 0 5 0 0
Eduardo Santos
Eduardo Santos am 4 Jan. 2021
Hi Adam, thanks for the answer. I was wondering something like your previous version but it works anyway.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by