Constantine
Constantine

Reputation: 7

Merging Two Arrays into One Cell

So I've been trying to figure this out for a few hours and I can't figure out how to get the format that I want.

I have an array x and y:

x=[39.8; 36.8; 36.6; 37.7]
y=[-56.7; -57.6; -60.2; -59.4]

I want to turn those two into a single array z, but in a single cell like this:

Single Column
-------------
39.8, -56.7

36.8, -57.6

36.6, -60.2

37.7, -59.4

Additionally I have a 24x1 double. It has a numbers of occurances, but is populated by mainly zeros. I want to put this is the next column over, but I know it needs to be the same length as the cords above. Is there a way to create an array with just the numbers >0?

Upvotes: 0

Views: 43

Answers (2)

Derek
Derek

Reputation: 657

Here solution which better scales to multiple arrays. On my machine, it is also faster.

x = [39.8; 36.8; 36.6; 37.7];
y = [-56.7; -57.6; -60.2; -59.4];
tic
for i = 1:1000
    X = num2cell(x);
    Y = num2cell(y);
    Z1 = strcat(X,Y);
end
toc
tic
for i = 1:1000
    Z2 = arrayfun(@horzcat, x, y, 'un', 0);
end
toc
assert(isequaln(Z1, Z2));

The timings:

Elapsed time is 0.106900 seconds.
Elapsed time is 0.017918 seconds.

Upvotes: 0

GameOfThrows
GameOfThrows

Reputation: 4510

How is this?

x=[39.8; 36.8; 36.6; 37.7]; y=[-56.7; -57.6; -60.2; -59.4];
X=num2cell(x);
Y=num2cell(y);
Z=strcat(X,Y);

whos Z:

 Name      Size            Bytes  Class    Attributes

 Z         4x1               304  cell       

Z{1}

ans =

39.8000  -56.7000

to get the Array without zeros, do something like:

ARRAY(ARRAY == 0 ) = [];

Upvotes: 1

Related Questions