Quickly split columns by columns

Suppose M and N are two arrays. In the simplest case M and N are like this:

1 14 7 80

2 15 8 12

3 16 9 11

(3 rows and 4 columns)

I want to split column 1 by All three columns , then split column 2 by “All three columns” and then split column 3 by “All” three columns.

What's the fastest way to do this? (Of course, using a for-loop is not a good algorithm.)

EDIT:

here is my code for the loop:

idx = 1;
for i = 1 : size(N,2)
   for j = 1 : size(M,2)
       u(:,idx)=N(:,i) ./ M(:,j);
       idx = idx + 1;
   end
end

      

+3


source to share


2 answers


How about using bsxfun

andpermute

Assuming M

both N

are equal and equalA

out = bsxfun(@rdivide, permute(A,[1 3 2]), A)

      

Input:



A =

 1    14     7    80
 2    15     8    12
 3    16     9    11

      

Results for your example:

out(:,:,1) =

1.0000    0.0714    0.1429    0.0125
1.0000    0.1333    0.2500    0.1667
1.0000    0.1875    0.3333    0.2727


out(:,:,2) =

14.0000    1.0000    2.0000    0.1750
7.5000    1.0000    1.8750    1.2500
5.3333    1.0000    1.7778    1.4545


out(:,:,3) =

7.0000    0.5000    1.0000    0.0875
4.0000    0.5333    1.0000    0.6667
3.0000    0.5625    1.0000    0.8182


out(:,:,4) =

80.0000    5.7143   11.4286    1.0000
6.0000    0.8000    1.5000    1.0000
3.6667    0.6875    1.2222    1.0000

      

+5


source


If a

A = [1 14 7 80

     2 15 8 12

     3 16 9 11]

      

Then

bsxfun(@ldivide, prod(A,2), A).*A

      



return

ans =

    0.0001    0.0250    0.0062    0.8163
    0.0014    0.0781    0.0222    0.0500
    0.0019    0.0539    0.0170    0.0255

      

So, the idea is to just split each element by ALL other elements of that string (i.e., by the product of the string, prod(A,2)

), and then just multiply by the original number to cancel the fact that you (i.e. .*A

in end). So, ans(2,3)

above 0.0222

, which is equal to (8/(2*15*8*12))*8

, where (2*15*8*12)

is the product of row 3.

NOTE. This answers the original question (i.e. the question you are describing) and does NOT answer the question of what your code means

+3


source







All Articles