How to use a for loop to display zeros of a function

Hello I am writing a small program in matlab to get familiar with it to find the zeroes of a function. Here is my problem, the program only displays 1 zero of the function and not all. Basically the program is displaying the last zero it finds instead of all the zeros. I am trying to modifiy it but it isn't working here is what I've got so far
function zerosOfF=zerosOfF(f);
N=max(size(f));
z=f(1);
for k=2:N
if f(k)*f(k-1)<0; z=-z; zerosOfF=k;
for zerosOfF=k:N
disp(zerosOfF);
end
end
end

 Accepted Answer

You've almost have it. The problem is that the code is overwriting each index whenever a zero (of f) is found rather than saving the index to a new element in the output array.
A couple of things - z is unused and so could be removed. Also, the output array variable is named the same as the function. To avoid confusion, it should be renamed.
Try the following
function indices=zerosOfF(f)
N=max(size(f));
% use this as an index into the output variable array
at = 0;
% initialize the output variable to an empty array
indices = [];
% iterate over each element
for k=2:N
if f(k)*f(k-1)<0;
at = at+1;
indices(at) = k;
end
end
Note that you should add additional logic to handle the first and last elements as they may not be captured in the above code.

2 Comments

Hello I am having trouble with the variable "at" what is it used for? Also the empty array why is it needed?
The variable at is used to insert the next zero of f into the output array indices
at = at+1;
indices(at) = k;
An alternative to this would be to just append the new index to the indices array at each iteration where a zero is found (avoiding the at altogether)
indices = [indices k];
It is a good habit to initialize variables to something before using them. In this case, I have chosen an empty array to handle the case where the input function f does not have any zeros. Suppose the code does not initialize indices to an empty array. Now try
u=zerosOfF([1 2 3 4])
I get the following error
Error in zerosOfF (line 3)
N=max(size(f));
Output argument "indices" (and maybe others) not assigned during call to
"/Users/geoff/Development/matlab/zerosOfF.m>zerosOfF".

Sign in to comment.

More Answers (0)

Categories

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

Asked:

on 16 Jul 2014

Commented:

on 16 Jul 2014

Community Treasure Hunt

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

Start Hunting!