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

1 次查看(过去 30 天)
%% 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);

采纳的回答

Walter Roberson
Walter Roberson 2020-7-11
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.

更多回答(1 个)

Image Analyst
Image Analyst 2020-7-11
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 个评论
Image Analyst
Image Analyst 2020-7-12
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 2020-7-12
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by