Addition of matrix in a loop

I have four matrix :
r1=[1 2 3 4 5];
r2=[3 4 5 6 7];
d1=2*r1+5
d2=5*r2-2;
I need to add these two matrix such that result matrix
d=d1+d2
for elements in
r1==r2 (for r1=r2=3,4,5)
and for
r1==[1,2], d=d1
and for
r2==[6,7], d=d2.
Result must get matrix should be 1x 7. I could add these a zeros matrix but want using loop which can be extend to any other matrix as well.
NB: Took the liberty to try to clarify a little as I understood the question--dpb

4 Comments

It worked for this vector. I will apply now this to my matrix function. Thanks a lot
It'll work for any set of vectors with the underlying pattern.
sagar pokhrel
sagar pokhrel on 30 Dec 2014
Edited: dpb on 31 Dec 2014
I tried to apply in my matrix which is multi-variate. It ended up with something else than expected.
theta=linspace(0,2*pi,73);
r=[0.5,1,1.5,2,2.5,3,3.5,4,4.5,5];
[theta,r]=meshgrid(theta,r);
[X,Y]=pol2cart(theta,r);
x=X(:)
y=Y(:)
% using another mat lab file a function is generated%
for i=1:length(x)
xa=x(i);
ya=y(i);
zest(i)=eqn1(xa,ya); %
end
Z=reshape(zest,73,10);
A=Z';
% similarly function B and function C are dependent on theta and r. All of %them are 10 x 73 matrix%
F1= A.*B.*C;
This gives functional value on each point of radius(0.5-5) for a source. Similarly for another source (1.5-6)functional(F2) value is calculated. I need to add F1 and F2 for same radius(1.5-5) and use F1( for <1.5) and F2( for >5) to create result matrix 12x 73. I couldn't use function handles here.
Thanks in advance.
Ya' lost me...don't see how the above matches the example's pattern nor quite follow what you're actually trying to do in the latter. Note, however, that intersect may not succeed with floating point comparisons owing to the vagaries of making floating-point tests for equality. The former example works because the vectors are integral values; for floating point for robustness you'll probably need to use a "fuzzy" compare.

Sign in to comment.

 Accepted Answer

First define a couple of useful function handles...
>> f1=@(x) 2*x+5;
>> f2=@(x) 5*x-2;
Then find the intersecting values...
>> xi=intersect(r1,r2);
and then build the output vector...
>> [f1(setdiff(r1,xi)) f1(xi)+f2(xi) f2(setdiff(r2,xi))]
ans =
7 9 24 31 38 28 33
>>

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 30 Dec 2014

Commented:

dpb
on 31 Dec 2014

Community Treasure Hunt

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

Start Hunting!