Triangle pyramid of numbers (0-9), but to return as output var.

10 views (last 30 days)
function [res]=WORKI_05(number)%NUMBER IS UNSIGNED INTEGER(TRIANGLE HEIGHT),RES IS MY OUTPUT.
value=int16(0);%MY TRIANGLE HAS VALUES FROM 0-9.
for i = 1 : number
for z=1:number-i
fprintf(' ');
end
for y=1:2*i-1
if value==10 %0-9 LOOP
value=0;
end
fprintf('%d',value);
value=value+1;
end
for j=1:number-i
fprintf(' ');
end
fprintf('\n') ;
end
end
But I need to use the function return value 'res', so my question is how to work with fprintf to save directly in var and then to return it.

Accepted Answer

Voss
Voss on 18 Dec 2021
See below for an example of how to do this with sprintf:
function [res]=WORKI_05(number)%NUMBER IS UNSIGNED INTEGER(TRIANGLE HEIGHT),RES IS MY OUTPUT.
res = repmat(' ',number,2*number+1);
value=int16(0);%MY TRIANGLE HAS VALUES FROM 0-9.
for i = 1 : number
% for z=1:number-i
% fprintf(' ');
% end
for y=1:2*i-1
if value==10 %0-9 LOOP
value=0;
end
% fprintf('%d',value);
res(i,number-i+y) = sprintf('%d',value);
value=value+1;
end
% for j=1:number-i
% fprintf(' ');
% end
% fprintf('\n') ;
end
end
See here for an example of how to do this without sprintf.

More Answers (1)

Image Analyst
Image Analyst on 18 Dec 2021
Edited: Image Analyst on 18 Dec 2021
You would use sprintf() instead of fprintf().
res = sprintf(..................)
  2 Comments
Image Analyst
Image Analyst on 18 Dec 2021
Then why did you accept Benjamin's answer? He told you to use sprintf() also:
res(i,number-i+y) = sprintf('%d',value);
Are you saying that sprintf() doesn't work? Obviously you were supposed to replace the dots in my code with whatever you had in fprintf(), so I'm assuming you did that.
However you tell me sprintf() does not work and you tell him it does work. Seems like a contradiction to me. OK, whatever, as long as you got it figured out.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!