ivbtar
ivbtar

Reputation: 879

fprintf is not working as expected in MATLAB

I have the below code in MATLAB. I use version R2019a.

clc;
clear all;
K = 100;
r = 5:1:55;
W = 10;
t = round((2*K.*r.^2+W^2)./60);
%disp("Turn : " + r + " " + t);
str = "Turn : ";
fprintf("%s %d %d",str,r,t)

I want to use fprintf instead of disp. r and t are 1x51 double variables.

screen shot of Workspace variable list

When I use fprintf without %s and str, the script prints 51 values one by one without a roblem. But if I use %s and str in fprintf it only prints the first line "Turn : 5 6 ", then it prints out strange characters as below.

screen shot of output of fprintf

If I use disp, it works correctly as below.

screen shot of output of disp

Upvotes: 0

Views: 933

Answers (2)

Paolo
Paolo

Reputation: 25989

You don't actually need any functions. When working with strings, if you use the + operator you get the conversion for free:

>> str + r + " " + t

ans = 

1×51 string array
Columns 1 through 5
"Turn : 5 85"    "Turn : 6 122"    "Turn : 7 165"    "Turn : 8 215"    "Turn : 9 272"
...

Upvotes: 3

Cris Luengo
Cris Luengo

Reputation: 60444

I was just reading this blog post by Loren Shure of the MathWorks. It taught me about compose. compose perfectly solves your problem. Use it instead of fprintf to combine your data into strings. Then use fprintf to print the strings to screen:

s = compose("%s %d %d", str, r.', t.');
fprintf("%s\n", s)

compose is much more intuitive than fprintf in how the values for each % element is taken from the input data. It generates one string for each row in the data. str is a scalar, its value will be repeated for each row. r.' and t.' here have the same number of rows, which will also be the number of rows in s.

Note: compose is new in MATLAB R2016b.

Upvotes: 4

Related Questions