concatenate arrays after performing addition

조회 수: 2 (최근 30일)
Neil Barker
Neil Barker 2019년 10월 15일
답변: Jos (10584) 2019년 10월 15일
I'm trying to add all the elements of A with element 1 of B. then do it again with element 2 etc. I'd like to concatinate the four 3x3 arrays into one array D (3x12). But i'm getting error messages.
This test code does what i want with array C, but i'm struggling getting all the previous FOR loops of C and the concatenation
A = [1,2,3;4,5,6;7,8,9];
B = [2,3,4,5];
C = zeros(3);
D = zeros(3,12);
for i = 1:numel(B)
C = A + B(i)
end
Thanks for any assistance you give,
Neil

채택된 답변

Andrei Bobrov
Andrei Bobrov 2019년 10월 15일
A = [1,2,3;4,5,6;7,8,9];
B = [2,3,4,5];
D = reshape(permute(A + reshape(B,1,1,[]),[2,1,3]),size(A,2),[])';
  댓글 수: 1
Neil Barker
Neil Barker 2019년 10월 15일
Thanks for your answer Andrei. I'll go through it now. My actual code will be A = NxN and
B = 1xN. so hopefully i'll be able to make a general case for D.
thanks again,
Neil

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

추가 답변 (1개)

Jos (10584)
Jos (10584) 2019년 10월 15일
A little simpler than all those permutes and reshapes:
A = [1 2 3 ; 4 5 6 ; 7 8 9] ;
B = [2 3 4 5] ;
C = repmat(A, numel(B), 1) + repelem(B(:), size(A,1), size(A,2))

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by