How to write to screen a set of variables with mixed types?

조회 수: 2 (최근 30일)
Robert Jones
Robert Jones 2024년 12월 30일
답변: Walter Roberson 2025년 1월 4일
hello,
I am trying to write to screen a set of variables with mixed types. I have the code below
and I get the following display:
d=0.7874 mm , epsr=2.1 >>
a='d=0.7874 mm , epsr=2.1';
m=3;
k=7;
u=7.853535;
fprintf('%s %i \t %10.5f \n',[a m u])
d=0.7874 mm , epsr=2.1□□
help would be appreciated.
Thank you
  댓글 수: 1
Stephen23
Stephen23 2024년 12월 30일
a='d=0.7874 mm , epsr=2.1';
m=3;
u=7.853535;
fprintf('%s %i \t %10.5f \n',a,m,u)
d=0.7874 mm , epsr=2.1 3 7.85353

댓글을 달려면 로그인하십시오.

답변 (2개)

Manikanta Aditya
Manikanta Aditya 2024년 12월 30일
편집: Manikanta Aditya 2024년 12월 30일
It looks like you're trying to print a string along with integer and floating-point variables using fprintf. The issue arises because you're trying to concatenate different types into a single array, which fprintf doesn't handle well. Instead, you should pass each variable separately to fprintf.
Here's how you can modify your code to correctly display the variables:
a = 'd=0.7874 mm , epsr=2.1';
m = 3;
k = 7;
u = 7.853535;
% Use fprintf with separate arguments for each variable
fprintf('%s %i \t %10.5f \n', a, m, u);
d=0.7874 mm , epsr=2.1 3 7.85353
This will correctly print the string a, the integer m, and the floating-point number u in the desired format.
If you want to include the variable k as well, you can add it to the fprintf statement:
fprintf('%s %i \t %i \t %10.5f \n', a, m, k, u);
d=0.7874 mm , epsr=2.1 3 7 7.85353
This way, each variable is passed as a separate argument to fprintf, ensuring they are printed correctly.
Refer to the following doc:
I hope this helps.

Walter Roberson
Walter Roberson 2025년 1월 4일
a='d=0.7874 mm , epsr=2.1';
m=3;
u=7.853535;
temp = [a m u]
temp = 'd=0.7874 mm , epsr=2.1□□'
length(a)
ans = 22
length(temp)
ans = 24
temp(end-1:end), temp(end-1:end)+0
ans = '□□'
ans = 1×2
3 7
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
You are using [] to concatenate a character vector and numeric items. As described in https://www.mathworks.com/help/matlab/matlab_prog/valid-combinations-of-unlike-classes.html the result of concatenating a character vector and numeric items is a character vector, with each of the numeric items having first been converted to uint16() after fractions are dropped. The numeric values are not first converted to printable representations: they are treated as code-points.
So you start with your vector of length 22, and concatenate on two code points, giving a result that is a vector of length 24, the last two code points of which are 3 and 7.
Your error was in concatenating the values first, instead of using individual parameters to fprintf()

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by