How do I make the same output using the fprintf() command instead of disp()?
Show older comments
Hello, this is my first question on here and I notice Answerers are sometimes frustrated by questions, so I hope this question does not anger anyone. I am trying to use fprintf() instead of the disp() and have the exact same output. Here's the editor window and output:
editor:
A = [1 2 3;4 5 6;7 8 9];
[m,n] = size(A);
for i = 1:m
for j = 1:n
disp(['A(',num2str(i),',',num2str(j),') = ',num2str(A(i,j))])
end
end
output:
>> Practice9
A(1,1) = 1
A(1,2) = 2
A(1,3) = 3
A(2,1) = 4
A(2,2) = 5
A(2,3) = 6
A(3,1) = 7
A(3,2) = 8
A(3,3) = 9
>>
%Also, this is what I attempted to do, but got a 'horzcat' error
%what is that???
A = [1 2 3;4 5 6;7 8 9];
[m,n] = size(A);
for i = 1:m
for j = 1:n
fprintf(['A(','(%s,','%s) = ','%f',i,j,A])
%% disp(['A(',num2str(i),',',num2str(j),') = ',num2str(A(i,j))])
end
end
6 Comments
You don't want square brackets in a fprintf. The first argument should just be a single char array (a string basically, but I'm not 100% sure if the string datatype is supported or not, which is why I call it a char array specifically) with the %s type things as you have for the formatting, but don't put it in square brackets to try to concatenate anything. It is a single string with formatted inputs defined, as you have done, by the subsequent arguments. That may not be the only problem, but it is the one I notice and that will likely lead to the horzcat error.
The whole thing needs to be a single string too e.g.
'A(%i,%i) = %f'
Guillaume
on 14 Nov 2018
As of R2018b, string arrays should be supported by all functions in matlab (toolboxes are another matter). Before R2018b support was a bit spotty but fprintf supported strings since they were introduced in R2016b.
Guillaume
on 14 Nov 2018
"Answerers are sometimes frustrated"
Actually, I think we're very tolerant. The thing that tend to frustrate us is people copy/pasting their homework question without even trying to solve it themselves or people saying it doesn't work without further explanation.
Your question is well detailed. Nobody is going to get frustrated by that.
madhan ravi
on 14 Nov 2018
see my answer below
Adam Hernandez
on 14 Nov 2018
Adam Hernandez
on 14 Nov 2018
Accepted Answer
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!