Adding elements of arrays conditionally
1 view (last 30 days)
Show older comments
Hi I have arrays x1, y1 of 10 elements each and arrays x2, y2 with 15 elements each. I also have array z1 which is 10 x 10 array, and z2 which is 15 x 15 (z1 elements corresponding to each combination of x1 and y1 indexes, and z2 corresponding to each combination of x2 and y2 indexes)
All the elements of x1 can be found in x2 (other 5 elements are randomly scattered between values which correspond to x1) Same goes for y1 and y2 as well.
For example:
x1 = [100,200,300,400,.....1000]
x2 = [100,150,200,300,400,450...1000,1100]
What I am trying to do is: depending on the value of x1 and y1, add the corresponding value of z1 to that of z2 (when a value of x1(n)=x2(m), and y1(a)=y2(b)). So basically if x1(n) == x2(m) && y1(a)==y2(b), then z3 = z1(n,a) + z2 (m,b)
I want to have an array built of z3 values (10x10).
I hope this question makes sense.
Are there any efficient and easy ways to implement this sort of approach in Matlab?
Many thanks
Answers (2)
Azzi Abdelmalek
on 20 Mar 2013
Edited: Azzi Abdelmalek
on 20 Mar 2013
EDIR
[xx1 yy1]=meshgrid(x1,y1);
[xx2 yy2]=meshgrid(x2,y2);
for k=1:10
for p=1:10
idx=find(xx2==xx1(k,p),1);
idy=find(yy2==yy1(k,p),1);
z3(k,p)=z1(idx)+z2(idy);
end
end
Azzi Abdelmalek
on 20 Mar 2013
Try this
[xx1 yy1]=meshgrid(x1,y1);
[xx2 yy2]=meshgrid(x2,y2);
for k=1:10
for p=1:10
[n,~]=find(xx2==xx1(k,p),1)
[~,b]=find(yy2==yy1(k,p),1)
z3(k,p)=z1(k,p)+z2(n,b)
end
end
See Also
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!