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?

 채택된 답변

Adam Danz
Adam Danz 2019년 4월 8일

1 개 추천

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

Thanks, it worked nicely.
Just wondering.. keeping the same idea but instead to keep the number, get only the numer 1 in the cell function, like:
ans =
1 1 1 1 1
0 1 1 1 1
0 1 1 1 1
0 0 1 1 0
0 0 1 0 0
What should I do?
B(B>0)=1; ?
Your solution above is one way to do it. If you don't need the original matrix in the first place and want to bypass that,
% |-------| This is the only change
base = cellfun(@(x)ones(x,1), num2cell(A), 'UniformOutput', false);
cell2mat(cellfun(@(y,n) padarray(y,n, 'post'),base, num2cell(max(A)-A), 'UniformOutput', false))
Eduardo Santos
Eduardo Santos 2020년 12월 24일
Hy Adam.
How can I change for
ans =
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
Cheers!
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 2021년 1월 4일
Hi Adam, thanks for the answer. I was wondering something like your previous version but it works anyway.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2019년 4월 8일

댓글:

2021년 1월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by