Is this program free from bugs? The program is to find the position of the element greater than 100.

1 visualizzazione (ultimi 30 giorni)
%% Example
for ii= 1:length(readings)
if readings(ii)>100
fprintf('first reading above 100 is at position %d\n', ii);
return;
end
end
fprintf('no values greater than 100 upto position %d\n',ii);

Risposta accettata

Walter Roberson
Walter Roberson il 11 Lug 2020
The program will not work properly if readings is two or more dimensional.
The program will fail when it encounters the return statement: return is only permitted in functions.
The program will fail if readings is something that is not comparable to a number, such as if it is a cell array or transfer function.

Più risposte (1)

Image Analyst
Image Analyst il 11 Lug 2020
If readings is a double array, you could do this:
index = find(readings > 100, 1, 'first');
if isempty(index)
fprintf('No value greater than 100 was found.\n');
else
fprintf('First value greater than 100 was found at index %d and has a value of %f.\n', index, readings(index));
end
  3 Commenti
Image Analyst
Image Analyst il 12 Lug 2020
It's normal for something to be printed, yes. That's what fprintf() does. If only the first fprintf() gets executed, then there are no values above 100. If the second one gets executed then there will be at least one value above 100. Here is a demo:
% First have no values more than 100
readings = [1,2,3,4]
index = find(readings > 100, 1, 'first');
if isempty(index)
fprintf('No value greater than 100 was found.\n');
else
fprintf('First value greater than 100 was found at index %d and has a value of %f.\n', index, readings(index));
end
% Now, have several values more than 100
readings = [1,2,3,400, 900, 7,6,5]
index = find(readings > 100, 1, 'first');
if isempty(index)
fprintf('No value greater than 100 was found.\n');
else
fprintf('First value greater than 100 was found at index %d and has a value of %f.\n', index, readings(index));
end
It prints the two cases to the command window:
readings =
1 2 3 4
No value greater than 100 was found.
readings =
1 2 3 400 900 7 6 5
First value greater than 100 was found at index 4 and has a value of 400.000000.
I guess I just don't see why this is confusing to you. Do you expect the second fprintf() to print even when there are no values above 100? If so, why? Please attach your readings and tell me what you think it should print.
Walter Roberson
Walter Roberson il 12 Lug 2020
When you talk about "publish the script" are you referring to Report Generator?
Note: it is an error to have a return statement in a script. return statements only belong in functions.

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by