Hello,
Is it possible using fprintf or another function to write both an array of strings and numerical values to a file? I would like to write the variables names as well as their numeric values.
Thank you, Kevin

 채택된 답변

José-Luis
José-Luis 2014년 6월 5일

0 개 추천

Yes you can:
s = 'I am a string';
n = pi();
fprintf(1,'%s %f',s,n); %Replace 1 with an actual fid

댓글 수: 4

Something's not working quite right. As an example, I have
syms a b c d e
alphabet = [a ; b; c ; d ; e]
numeric = [1 ; 2; 3; 4 ; 5]
fid = fopen('Test.txt','w+')
fprintf(fid,'%s %f',char(alphabet),numeric)
Test = fscanf(fid,'%s %f')
I need to be able to write and read "alphabet" and "numeric" because I need to exchange this data this way using TCP/IP communication.
Don't have alphabet after the format string, put it inside :
fprintf(fid,'alphabet %f %f %f %f %f', numeric)
Either way you're typing it into that line of code, but where you put it makes all the difference.
That works, but what would I do if I didn't know the number of elements in alphabet?
That won't happen. You will know the name of your variable. If your variable name itself is variable, and stored in a variable, like your variable name is myVariableName, and sometimes that will contain the string 'alphabet' and other times it might contain 'starTrek' and other times it might be 'starWars', then treat it just as an ordinary string
fprintf(fid,'%s %f %f %f %f %f', myVariableName, numeric)
so you'll see starTrek, alphabet, or starWars depending on what happened to be inside the string. But you will and must know that the variable is called myVariableName, otherwise how can you possibly tell it what to write out?

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

추가 답변 (1개)

Star Strider
Star Strider 2014년 6월 5일

1 개 추천

If you are exchanging files with someone else who is using MATLAB, use a mat-file. They are easy to use, binary, so are smaller, and do not need formats to write or read. They also associate the variables with their values, and when the files are opened, the variables and values (string, symbolic, numeric, cell) are automatically loaded into the workspace of the function calling them.
See matfile and associated functions for details.

댓글 수: 1

mat-files are very helpful. Unfortunately in this case, I need to exchange variables and values between processors using TCP/IP communication.

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

카테고리

도움말 센터File Exchange에서 Workspace Variables and MAT Files에 대해 자세히 알아보기

질문:

2014년 6월 5일

댓글:

2014년 6월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by