fprintf in a for loop printing repetitive answers in command window
Show older comments
Hi i'm working on a function that selects the peaks from a data and prints the coordinates of each peak. Also it marks the peaks in a plot.
When I run the program the plot looks great but there are repetitive answers in the Matlab command window. My program is the following:
clear all
close all
clc
n=10;
b = randn(n,1);
a = cumsum(b);
da = diff(a);
plot(a);
hold on;
i=1;
if da(i) < 0
harm = a(i);
freq = i;
plot(freq,harm,'ro');
hold on
fprintf('Harmonic of Amplitude %.2f at %d Hz\n',harm,freq)
i = i + 1;
end
for i = i:n-1
while i < n-1
if ((da(i) > 0) && (da(i+1) < 0))
harm = a(i+1);
freq = i+1;
plot(freq,harm,'ro');
hold on
fprintf('Harmonic of Amplitude %.2f at %d Hz\n',harm,freq)
i = i + 1;
else i = i + 1;
end
end
end
if da(n-1) > 0
harm = a(n);
freq = n;
plot(freq,harm,'ro');
hold on
fprintf('Harmonic of Amplitude %.2f at %d Hz\n',harm,freq)
end
The command window give this results:
Harmonic of Amplitude 0.57 at 1 Hz Harmonic of Amplitude -0.19 at 9 Hz Harmonic of Amplitude -0.19 at 9 Hz Harmonic of Amplitude -0.19 at 9 Hz Harmonic of Amplitude -0.19 at 9 Hz Harmonic of Amplitude -0.19 at 9 Hz Harmonic of Amplitude -0.19 at 9 Hz Harmonic of Amplitude -0.19 at 9 Hz
What it happening that the program gives the results repeated?
1 Comment
Jiro Doke
on 23 Feb 2011
Can you edit this question and use appropriate formating. Highlight the text that represents MATLAB code, and click on the {}Code button.
Answers (2)
Sean de Wolski
on 23 Feb 2011
Your values: harm, freq are probably not scalars and thus it's printing multiple times to show all contents.
Use
num2str(harm)
and the %s operator to show both values in one location. e.g.
fprintf('Hello World: %s\n',num2str(harm))
%SCd
Matt Tearle
on 23 Feb 2011
Your code is hard to read b/c of the formatting, but it seems to me that you're trying to do something very similar to this other answer. In which case... can I suggest a much neater version, that also isn't producing repeat display lines (at least not for me):
n=10; b = randn(n,1); a = cumsum(b); da = diff(a);
idx = [da(1)<0; da(2:end)<0 & da(1:end-1)>0; da(end)>0];
nmax = find(idx);
amax = a(idx);
plot(1:n,a,'o-',nmax,amax,'rx')
fprintf('Harmonic of Amplitude %.2f at %d Hz\n',[amax';nmax'])
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!