Why isn't addition working for this equation

My script is not giving me the correct calculations
clear all
x = 0:50
y = 0:30
[X,Y] = meshgrid(x,y)
L1 = sqrt(((X-5).^2)+((Y-5).^2));
L2 = sqrt(((X-10).^2)+((Y-20).^2));
L3 = sqrt(((X-30).^2)+((Y-10).^2));
L = L1+L2+L3
If I do L1+L2 only, the sum is correct. However, when I do L1+L2+L3, the values I get are completely wrong and much less than L1+L2, which makes no sense at all.
Any help please.

Answers (3)

You do not explain how you come to the statement, that L1+L2+L3 is "completely wrong" and even smaller than L1+L2. I cannot observe this and I agree that this would not make sense at all:
[X,Y] = meshgrid(0:50, 0:30);
L1 = sqrt(((X-5).^2)+((Y-5).^2));
L2 = sqrt(((X-10).^2)+((Y-20).^2));
L3 = sqrt(((X-30).^2)+((Y-10).^2));
L12 = L1 + L2;
min(L12(:)) % 15.8113883008419
max(L12(:)) % 92.7092069611116
L123 = L1 + L2 + L3;
min(L123(:)) % 36.1585432929098
max(L123(:)) % 120.993478208574
any(L123(:) < L12(:)) % false
This looks fine. Nothing gets smaller. Everything looks completely correct. Therefore I assume, that your test is wrong, not the values.
x = 0:50
y = 0:30
[X,Y] = meshgrid(x,y)
L1 = sqrt(((X-5).^2)+((Y-5).^2));
L2 = sqrt(((X-10).^2)+((Y-20).^2));
L3 = sqrt(((X-30).^2)+((Y-10).^2));
L12 = L1+L2;
L123 = L1+L2+L3;
Run that code. Please tell us the index of a specific element in L12 and L123 where the value is "completely wrong" and show us the values in L1, L2, L3, L12, and L123 for that specific index, something like:
L123(2, 3) is not what I expect. I expected it to be 73.
>> [L1(2, 3); L2(2, 3); L3(2, 3); L12(2, 3); L123(2, 3)]
ans =
5.0000
20.6155
29.4109
25.6155
55.0264
If your X and Y matrices were square, I would have guessed you had used the ^ operator (matrix power) instead of the .^ operator (element-wise power) in computing L3. If you changed the x and y vectors when you copied the example from MATLAB to Answers, you may want to double-check that.
Thanks for taking the time to answer guys.
Basically, L1+L2 gave a value of around 70 or so for the last output when I ran the code, which is correct. But when I did L1+L2+L3, the very last output was a value around 1.2, which is definitely wrong. After trying to sum it up using different methods, none of which worked, I decided to restart MatLab. I loaded my script again and ran it, and everything worked as it should have. I suspect I had the program running for too long and had too many variables, commands, and output, so it started to get buggy.

Categories

Tags

No tags entered yet.

Asked:

on 28 Apr 2017

Answered:

on 28 Apr 2017

Community Treasure Hunt

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

Start Hunting!