2

I have a matrix d whose dimensions are 2 X 2 X 1000

d(:,:,1)= [ a1 b1
            c1 d1]

d(:,:,2)= [ a2 b2
            c2 d2]

And I have a array u 1 X 1000

 u=[u1 u2 ... u1000] . 

I want to create a matrix M where each element of M is equal to an element of the matrix in the matrix d elevated at the correspondent element in U vector.

 M = [ a1^u1*a2^u2*...a1000^u1000   b1^u1*b2^u2*...b1000^u1000 
       c1^u1*c2^u2*...c1000^u1000   d1^u1*d2^u2*...d1000^u1000 ]

And I tried to write this code:

  n_length =2 
    for k=1:length(d)
    for i = 1:n_length
         for j = 1:n_length

            M(i,j)= prod(d(i,j,k)^u(1,k));

         end 
    end
    end

But there is something wrong. Although there is no error but the output is not as expected. I think I made a mistake in implementing the equations above. Could anyone help me to combine the d and U by the above method ?

1
  • "there is something wrong" Please include a complete error description. Commented Apr 25, 2017 at 8:47

2 Answers 2

2

You can use bsxfun to perform element-wise power computations of d to u and then use prod to reduce to 2D, like so -

prod(bsxfun(@power,d,permute(u,[1,3,2])),3)

Sample run -

>> d
d(:,:,1) =
    0.3000    0.2000
    0.4000    0.5000
d(:,:,2) =
    0.6000    0.2000
    0.3000    0.5000
d(:,:,3) =
    0.4000    0.3000
    0.7000    0.2000
>> u
u =
     2     3     2
>> 0.3^2*0.6^3*0.4^2 % First output elem
ans =
    0.0031
>> 0.5^2*0.5^3*0.2^2 % Last output elem
ans =
    0.0013

>> prod(bsxfun(@power,d,permute(u,[1,3,2])),3)
ans =
    0.0031    0.0000
    0.0021    0.0013
Sign up to request clarification or add additional context in comments.

Comments

1

Here is your solution:

Write a generic function for the operation you want to do. example:

%% generate random data of given dimensions
d = rand(2,2,1000);
u = rand(1,1000);

%% create your function 
myFunction = @(dVal,uVal)  dVal.^uVal;

%% perpare u to match the third dimension of d
Ushifted = shiftdim(u,-1); % turns U from 1X1000 to 1X1X1000

now you that the 3rd dimension of your matrices matches (both 1000), bsxfun will run the function for each of the 1000 elements (2x2 matrix of d, vs single value of U).

M = bsxfun(@(d,u) myFunction(d,u),d,Ushifted); % U is 2X2X1000
M = prod(M,3); % computes the product on the third dimension (1000)

1 Comment

thanks , but I just want to get 1 final combined M matrix with the size of (2x2) . Not 1000 matrices with the size of (2x2).

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.