Concatenate logical/numerical arrays element wise

5 views (last 30 days)
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
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
Any help would be appreciated. I have tried many examples to concatenate without any success.
Aiman Raza
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.

Sign in to comment.

Accepted Answer

James Tursa
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
ans = 3×1 logical array
1 1 0
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:
ans = 3×1 logical array
1 1 0
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:
ans = 1×3 logical array
1 1 0
ans = 1×3 logical array
0 1 1

More Answers (0)

Community Treasure Hunt

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

Start Hunting!