user162343
user162343

Reputation: 209

Using MATLAB to compute all the integers the satisfy a condition

I want to compute using MATLAB all the integers x such that x^2-2x<2000, but I am having problems in the displaying part because when I run my code MATLAB seems not to finish. My code is as follows:

x=100;
    while x^2+2x-2000>=10^-6
        x=x-20;
    if x^2+2x-2000<10^-6
            disp(x)
        end

    end

I think the wrong part is when I type disp(x) in the while loop, but I don't know how to fix it.

NOTE: I am using the 10^-6 to avoid rounding errors

Can someone help me to fix this code please?

Upvotes: 0

Views: 58

Answers (3)

user3667217
user3667217

Reputation: 2192

Computationally, finding all integers that satisfy this condition will need some help from a quick insight into this problem. Otherwise, you'll have to test all the integers, which is impossible since there is infinite number of integers. Analytically, finding all the integers that satisfy the condition x^2-2x < 2000 means finding the integers that lies within the intersection of the curve x^2 - 2x and y = 2000.

Let's first take a look at the problem by plotting it:

x = -500:.1:500;
y = x.^2 - 2*x;
plot(x, y, 'color', 'g')
hold on
line([-200 200], [2000 2000], 'color', 'r')

enter image description here

You can easily see that you can limit your search to at least between -100 and 100. You can store the value in an array

results = []    % Declare empty array first and append value later. 
for x = -100:100
    if x^2 - 2*x < 2000
        disp(x)
        results = [results,x];  % Using a bracket to append value to the array.
    end
end

And a faster way to get results using logical indexing.

x = -100:100
results = x(x.^2 - 2*x<2000)

In the above code, x.^2 - 2*x < 2000 generates a logical array that has the same size as x. Each element stores the logical value that comes from the evaluating each element in x with the expression. You then use this as a mask to pick out only elements in x that satisfy this condition.

Upvotes: 1

Adriaan
Adriaan

Reputation: 18177

Building upon @User3667217's solution, you can also vectorise this:

x = -100:100;
y = x.^2-2*x;
tmp = y<2000;
results = y(tmp);

this will give you a speed up over the for-loop solution.

Upvotes: 1

chris
chris

Reputation: 4996

If you add in some parentheses and use the correct syntax for 2*x, it works.

x=100;
while (x^2+2*x-2000)>= (10^-6)
    x=(x-20);
if (x^2+2*x-2000) <10^-6
        disp(x)
    end

end

Upvotes: 1

Related Questions