How to merge two column cell arrays into one, with alternating values?

A = ones(5,1);
B = zeros(5,1);
Assuming A and B will always be the same size, how can I get the result? I can't seem to find the right way of using reshape to achieve this.
C = {1 0 1 0 1 0 1 0 1 0}
Thanks in advance

4 Kommentare

I think you meant to merge two vectors. Cell arrays are different data types. Anyways, here is the reshape you want
% Specify [] for the first dimension to let reshape automatically
% calculate the appropriate number of rows.
% 1 is the number of column
c = reshape([A B]',[],1)
c = c'
Thanks! I did mean cell arrays, but I realize that the example I gave was numeric. Your answer works for cell arrays also.
A = {'a', 'b', 'c', 'd', 'e'};
B = {'1','2','3','4','5'};
C = reshape([A B]', [], 1)'
If you want to add your response as an answer, I will accept it. Thanks!
No need for the second transpose, just specify the desired output size when reshaping:
C = reshape([A,B].',1,[])
You are welcome @Jerki Jokne. It’s good that you got the result.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

I would create a matrix with size a+b then fill it in using steps of two.
a=zeros(1,5);
b=ones(1,5);
c= zeros(1,size(a,2)+size(b,2));
c(1:2:end)=a;
c(2:2:end)=b;

Kategorien

Tags

Gefragt:

am 11 Aug. 2021

Beantwortet:

am 11 Aug. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by