All my points are not showing up after for-loop
1 次查看(过去 30 天)
显示 更早的评论
I have three matrixes. One with x values, one for y values and a last for mass. Where the mass in point (1,1) is located in the location given by x(1,1) and y(1,1).
I am trying to create a new matrix showing the mass combined in a map grid.
[xi,yi] = meshgrid(300:0.25:380,0:0.25:90);
B = zeros(size(yi,1),size(xi,2));
for i = 1: size(xi,2)
for j = 1: length(yi)
m = find((x<(xi(1,i)+0.1250)) & (x>(xi(1,i))-0.1250));
n = find((y<(yi(j,1))+0.1250) & (y>(yi(j,1))-0.1250));
if length(m)<=length(n)
for k = 1:length(m)
if m(k) == n(k)
B(j,i) = B(j,i) + bmass(m(k));
end
end
end
if length(m) > length(n)
for k = 1: length(n)
if n(k) == m(k)
B(j,i) = B(j,i) + bmass(n(k));
end
end
end
end
end
when finished my new matrix B only contains 170 points which are non-zero. I know that in my bmass variable has over 60'000 values, and all should be located in the region of interest.
Thanks for any advice to how to improve code (new to matlab, so any comments on how to improve is welcome)
0 个评论
采纳的回答
Ghada Saleh
2015-7-20
Hi Elise,
It is my understanding that you are not getting all the points that satisfy the constraint copied in B. I believe this issue is because of the imposed condition in "if m(k) == n(k)". I understand that you want to make sure the point satisfies the condition on 'x' and 'y'. However, this condition add an additional constraint, that is MATLAB needs to find the point in exactly the same order for 'x' and 'y'. To illustrate; consider the following values for 'm' and 'n':
m = [1 5 7 11];
n = [2 7 12];
In this case, the position 7 in 'bmass' should be copied to 'B', however since you are comparing 'm(1) & n(1), m(2) & n(2), m(3) & n(3)' only, your code will not copy that position. To solve this issue, consider using ismember function instead. An example of how to do this is as follows:
for i = 1: size(xi,2)
for j = 1: length(yi)
m = find((x<(xi(1,i)+0.1250)) & (x>(xi(1,i)-0.1250)));
n = find((y<(yi(j,1))+0.1250) & (y>(yi(j,1))-0.1250));
pos = n(ismember(n,m));
for k = 1:length(pos)
B(j,i) = B(j,i) + bmass(pos(k));
end
end
end
Note that, you do not need to compare the lengths of 'm' and 'n' when using 'ismember'.
I hope this helps,
Ghada
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!