Matrix manipulation such as subtraction

Can I ask for some help regarding matrix manipulation? Here's what I'm after. Let's say for example I have two arrays:
A = [2 3 4 5]
B = [0 1 2 3 4 5 6 7 8 9]
The output that I want is a cell containing an answer like this:
C{1} = [2-0 3-0 4-0 5-0]
C{2} = [2-1 3-1 4-1 5-1]
.
.
.
C{10} = [2-9 3-9 4-9 5-9]

 Accepted Answer

A = [2 3 4 5] ;
B = [0 1 2 3 4 5 6 7 8 9];
out=arrayfun(@(x) A-x,B,'un',0);
celldisp(out)
%or
A = [2 3 4 5];
B = [0 1 2 3 4 5 6 7 8 9];
out1=bsxfun(@minus,A,B')
out=num2cell(out1,2);
celldisp(out)

9 Comments

can you explain to me how it works? Thanks
doc bsxfun
doc arrayfun
doc cellfun
Thanks for that. I have another question.
Example I already have an output1 and output2 which are both cells as a result of the codes that you've provided above. Both output1 and output2 are 1x2 cells (each cell element contains 1x6 array).
How will I be able to get the quadratic sum of the two cells and store it again in an array? Thanks
Provide a short example
out{1}(1) = sqrt((output1{1}(1))^2 + (output2{1}(1))^2)
out{1}(2) = sqrt((output1{1}(2))^2 + (output2{1}(2))^2)
.
.
.
out{2}(1) = sqrt((output1{2}(1))^2 + (output2{2}(1))^2)
out{2}(2) = sqrt((output1{2}(2))^2 + (output2{2}(2))^2)
Example
out1={1:6 11:16}
out2={2:7 12:17}
out=cellfun(@(x,y) bsxfun(@hypot,x,y),out1,out2,'un',0)
what if I have three cells? should I just change the code to this?
out=cellfun(@(x,y,z) bsxfun(@hypot,x,y,z),out1,out2,out3,'un',0)
I've tried it but it gives me an error saying:
Error using bsxfun
Too many input arguments.
Error in @(x,y,z)bsxfun(@hypot,x,y,z)
out1={1:6 11:16}
out2={2:7 12:17}
out3={3:8 13:18}
out=cellfun(@(x,y,z) sqrt(x.^2+y.^2+z.^2),out1,out2,out3,'un',0)
Thank you very much for the help :D

Sign in to comment.

More Answers (1)

Faster:
your_mat = repmat(A,numel(B),1)-repmat(B',1,numel(A));

Categories

Asked:

on 19 Dec 2013

Commented:

on 19 Dec 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!