Create a matrix from 2 vectors
조회 수: 10 (최근 30일)
이전 댓글 표시
I have a vector A =[ 1;3;1;4] and a vector B = [ 8,9,9,6]. The values of A must increase one by one till reaching the value speficied in B, then, how can I obtain the following matrix:
[1 2 3 4 5 6 7 8 0; 3 4 5 6 7 8 9 0 0; 1 2 3 4 5 6 7 8 9; 4 5 6 0 0 0 0 0 0]
without using a for loop?
Thank your very much for your help
댓글 수: 0
채택된 답변
Star Strider
2017년 1월 8일
This creates your matrix with an expressed loop, however there are obviously loops within the functions.
The Code —
A = [ 1;3;1;4];
B = [ 8,9,9,6];
C = ones(size(A,1), max(B));
C = cumsum(C,2);
C = bsxfun(@plus, C, A-1);
I = bsxfun(@le, C, B(:));
C = C.*I % Desired Result
C =
1 2 3 4 5 6 7 8 0
3 4 5 6 7 8 9 0 0
1 2 3 4 5 6 7 8 9
4 5 6 0 0 0 0 0 0
The ‘C’ matrix is (obviously) the output.
댓글 수: 6
추가 답변 (1개)
Guillaume
2017년 1월 8일
There is nothing wrong with using loops when they make the code clearer. This is, arguably, the most efficient loop version:
C = zeros(numel(A), max(B(:) - A(:)) + 1);
for row = 1:numel(A)
C(row, 1:B(row)-A(row)+1) = A(row):B(row);
end
Another option, not using explicit loops, shorter but probably far less efficient than Star's answer:
ncols = max(B(:) - A(:)) + 1;
C = cell2mat(arrayfun(@(s, e) [s:e, zeros(1, ncols-e+s-1)], A, B(:), 'UniformOutput', false))
댓글 수: 1
참고 항목
카테고리
Help Center 및 File Exchange에서 Performance and Memory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!