How do i mix two different size arrays i.e A=[a1 a2 a3...a12] and B=[b1 b2 b3...b9] so that the resulting one is C={a1 b1 a2 b2 a3 b3...] and the longer vector is the ones whos values continue when the shorter one is exhausted of values. I also need to do this using horizontal concatenation, horzcat, reshape, lengths, zeros and ones matricies and other commands.

 採用された回答

Stephen23
Stephen23 2023 年 9 月 19 日

0 投票

A = rand(1,3)
A = 1×3
0.7096 0.8827 0.4324
B = rand(1,7)
B = 1×7
0.4981 0.1477 0.8535 0.7647 0.1932 0.2252 0.5484
N = min(numel(A),numel(B));
C = [reshape([A(1:N);B(1:N)],1,[]),A(N+1:end),B(N+1:end)]
C = 1×10
0.7096 0.4981 0.8827 0.1477 0.4324 0.8535 0.7647 0.1932 0.2252 0.5484

5 件のコメント

tori lansing
tori lansing 2023 年 9 月 19 日
Thank you so much! That worked! I do want to ask you if the final line can be broken into two separate lines and ran separately, is that possible or is it specifically written to be ran together?
Stephen23
Stephen23 2023 年 9 月 19 日
"I do want to ask you if the final line can be broken into two separate lines and ran separately, is that possible or is it specifically written to be ran together?"
The last line consists of one concatenation (of three arrays), which of course you could "break" into several seprate lines before concatenating together. What do you hope to gain by doing so?
tori lansing
tori lansing 2023 年 9 月 20 日
I want to be able to understand the different parts of the code. I am really new to Matlab and have not the slightest idea of what things do so I like to break them down to understand whats going on.
Stephen23
Stephen23 2023 年 9 月 20 日
"I want to be able to understand the different parts of the code."
It is often useful to "break" down code when debugging or trying to understand code:
A = rand(1,3) % fake data (row vector)
A = 1×3
0.7642 0.3381 0.8769
B = rand(1,7) % fake data (row vector)
B = 1×7
0.4824 0.7981 0.5552 0.6184 0.0284 0.1195 0.3547
N = min(numel(A),numel(B)) % N = shortest vector length
N = 3
M = [A(1:N);B(1:N)] % 2xN matrix
M = 2×3
0.7642 0.3381 0.8769 0.4824 0.7981 0.5552
R = reshape(M,1,[]) % 1x(2*N) vector... but note the order!
R = 1×6
0.7642 0.4824 0.3381 0.7981 0.8769 0.5552
X = A(N+1:end) % remaining elements
X = 1×0 empty double row vector
Y = B(N+1:end) % remaining elements
Y = 1×4
0.6184 0.0284 0.1195 0.3547
C = [R,X,Y] % join them all together
C = 1×10
0.7642 0.4824 0.3381 0.7981 0.8769 0.5552 0.6184 0.0284 0.1195 0.3547
tori lansing
tori lansing 2023 年 9 月 20 日
That helps a lot, thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

リリース

R2023a

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by