0

How would I go about mapping the values of TWO arrays to a function and returning the result as an array?

arr = [1, 2, 3];
arr2 = [1, 4, 5];

val= arrayfun(@(x) func(arr, arr2))

function val = func(x, y)
// Takes in two arrays, and does a double 'for' loop
// for all values in x, for all values in y, do x*y

So basically I would end up with an array of X Y val:

1    1    1    2    2    2    3    3    3    <- X values
1    4    5    1    4    5    1    4    5    <- Y values
1*1, 1*4, 1*5, 2*1, 2*4, 2*5, 3*1, 3*4, 3*5  <- X*Y values

Thanks.

EDIT - Updated desired output array

4
  • you want the resultant array to store the product? Commented May 17, 2013 at 4:58
  • Not exactly, there will be a different formula in func. I am just using the product as an example.
    – Travv92
    Commented May 17, 2013 at 5:07
  • well this could be implemented with nested for loops,which you already know,what's the difficulty that you're facing? Commented May 17, 2013 at 5:17
  • Sorry, I wasn't clear enough. I'm very new to Matlab and have no idea how I would go about producing the resulting array.
    – Travv92
    Commented May 17, 2013 at 5:23

2 Answers 2

0
             arr=[1,2,3];
             arr2=[1,4,5];
             product=zeros(1,9);
             index=1;
             for i=1:length(arr)
               for j=1:length(arr2)
                  product(index)=arr(i)*arr2(j);
                  index=index+1;
               end
             end

try the above code.

0
0

You could proceed this way:

res = arrayfun(@(i) arr(i).*arr2,1:numel(arr),'UniformOutput',0);
final_res = cat(2,res{:});

I hope this helps.

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.