# Concatenate logical/numerical arrays element wise

5 views (last 30 days)
Aiman Raza on 27 Jul 2022
Commented: Aiman Raza on 28 Jul 2022
I have five 2D arrays (912384x224) with either a logical 1 or 0 (essentially five logical masks). The five arrays are stored together in a single cell.
I wish to combine the logical arrays such that I have a new cell that combines the 1s and 0s of each array.
For example, if
H{1}(1,1)=1;
H{2}(1,1)=0;
H{3}(1,1)=1;
H{4}(1,1)=1;
H{5}(1,1)=0;
then the new cell array should be:
combinedH{1}(1,1)=[1,0,1,1,0] (or just 10110)
If I do the regular cat function, the arrays do not merge element-wise. Converting the values to string and then back to double after concatenation is memory consuming.
I can obtain the desired result through the below code, but it is also incredibly time-consuming.
for m=1:912384
for n=1:224
end
end
Any help would be appreciated. I have tried many examples to concatenate without any success.
Regards
##### 2 CommentsShowHide 1 older comment
Aiman Raza on 28 Jul 2022
Thanks for your reply. This was what I was looking for. I will use the concatenated matrix to create a binary sequence, which I will multiply further with a data matrix (double) of the same size.

James Tursa on 27 Jul 2022
Edited: James Tursa on 27 Jul 2022
Here is one way:
% Generate sample data
H{1} = rand(2,3)<0.5;
H{2} = rand(2,3)<0.5;
H{3} = rand(2,3)<0.5;
Hc = cat(3,H{:}) % combined
Hc = 2×3×3 logical array
Hc(:,:,1) = 1 0 0 0 0 1 Hc(:,:,2) = 1 1 0 1 0 1 Hc(:,:,3) = 0 1 0 1 1 0
% Extract a vector of the original data
squeeze(Hc(1,1,:))
ans = 3×1 logical array
1 1 0
squeeze(Hc(1,2,:))
ans = 3×1 logical array
0 1 1
Or you could permute the vectors into the 1st dimension. E.g.,
Hp = permute(Hc,[3,1,2]);
Then extraction is on the 1st dimension and doesn't need squeezing:
Hp(:,1,1)
ans = 3×1 logical array
1 1 0
Hp(:,1,2)
ans = 3×1 logical array
0 1 1
And yet another way if you want row vector output is to permute your vectors into the 2nd dimension. E.g.,
H2 = permute(Hc,[4,3,1,2]);
Then extraction is on the first two dimensions:
H2(:,:,1,1)
ans = 1×3 logical array
1 1 0
H2(:,:,2,1)
ans = 1×3 logical array
0 1 1