How to print NaN for unexist value instead of error message

10 views (last 30 days)
Is there any way to print NaN instead of error message due to the two matrix are not valid.. For example, in this simple codes
clc, clear all
x = [1,2,3,4,5];
y = [3,4,5,6,7];
for i = 1: length(x)
out = x(i)+y(i+1);
fprintf('%.0f \t', out)
end
On other hand, please do not recommended me to do like this,
clc, clear all
x = [1,2,3,4,5];
y = [3,4,5,6,7];
for i = 1: length(x)-1
out = x(i)+y(i+1);
fprintf('%.0f \t', out)
end
fprintf('NaN \t')
---- result should be
5 7 9 11 NaN
I'm looking for trick which is fancy and more professional to fill unexcist variable by printing word like "NaN"

Accepted Answer

Star Strider
Star Strider on 2 Jul 2017
Try this:
x = [1,2,3,4,5];
y = [3,4,5,6,7];
for i = 1: length(x)
try
out = x(i)+y(i+1);
catch
out = NaN;
end
fprintf('%.0f \t', out)
end

More Answers (0)

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!