2

This is an updated version of the question Merge two arrays Matlab

Suppose the two arrays are now

    A1 = [x1 y1
          x2 y2
          x3 y3
          0  0
          0  0
          0  0
          0  0
          0  0
              ]

and

   A2 = [a1 b1
          a2 b2
          a3 b3
          a4 b4
          0  0
          0  0
          0  0
              ]

Now, how to merge A1 and A2 in the shortest way, such that

   A = [x1 y1
        x2 y2
        x3 y3
        a1 b1
        a2 b2
        a3 b3
        a4 b4
        0  0]

The earlier answer was correct and it removes all the zeros. But how to achiev this in the shortest way by indexing , similar to the previous answer?

Update :

This is what I tried Using the answer from the previous question

    A=[A1(max(A1')>0,:);A2(max(A2')>0,:)]
    A = padarray(A,[size(A1,1) - size(A,1) 0],'post')

It is pretty trivial, but as I have mentioned in my question clearly, is there an one line answer or a command that can achieve this like the previous question? My main aim is to expand my knowledge base on how to effectively use the indexing advantage of matlab and act as a guide for others as well who will come across this question, with many suggestions it may have.

Thanks, LN

6
  • how is the amount of zeros at the end determined? Commented Apr 30, 2014 at 14:53
  • it is just the size of A1. Please check the size of A1 and A2. Commented Apr 30, 2014 at 14:54
  • 3
    well, this looks like a pretty trivial extension of your previous question. Why don't you try to work out the solution yourself, then you ask here if something goes wrong? Commented Apr 30, 2014 at 14:57
  • I tried, and got a long way out. Am new to this @Acorbe, exp indexing arrays and was facing a deadline. So was not able to try new things. Am sorry if am asking too much. Commented Apr 30, 2014 at 15:07
  • 1
    please check the edits @Peter I hope am able to convince you guys that I tried something. Commented Apr 30, 2014 at 15:38

3 Answers 3

2

How about:

A2(length(A1),2) = 0;
A = A1 + circshift( A2,find(A1(:,1),1,'last'))
Sign up to request clarification or add additional context in comments.

Comments

1

An alternative to thewaywewalk's answer is:

A = zeros(size(A1)); 
A(1:nnz([A1;A2])/2,:) = reshape(nonzeros([A1;A2]),[],2)

Comments

0

Based on Robert P.'s answer (as the OP requested a one line answer):

A = [reshape(nonzeros([A1;A2]),[],2); zeros(size(A1,1) - nnz([A1;A2])/2, 2)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.