How to use a for loop to display zeros of a function
12 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Geoff Hayes
on 16 Jul 2014
Edited: Geoff Hayes
on 16 Jul 2014
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
Geoff Hayes
on 16 Jul 2014
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".
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!