Help with the fscanf function

8 ビュー (過去 30 日間)
AMZ
AMZ 2022 年 11 月 10 日
編集済み: Walter Roberson 2022 年 11 月 10 日
Hello Community,
I have been trying to figure out how I can use the fscanf functions to input data:
4 6
5.2 1.3
6.2 8.8
4.9 6.9
10.2 1.2
In this format:
A B
K1 J1
K2 J2
K3 J3
K4 J4
i.e. A = 4, B = 6, K1 = 5.2 etc..

採用された回答

Walter Roberson
Walter Roberson 2022 年 11 月 10 日
Call fscanf() with size parameter [2, inf] and use .' to transpose the output to N x 2
S = ...
"4 6" + newline + ...
"5.2 1.3" + newline + ...
"6.2 8.8" + newline + ...
"4.9 6.9" + newline + ...
"10.2 1.2"
S =
"4 6 5.2 1.3 6.2 8.8 4.9 6.9 10.2 1.2"
data = sscanf(S, '%f %f', [2 inf]) .'
data = 5×2
4.0000 6.0000 5.2000 1.3000 6.2000 8.8000 4.9000 6.9000 10.2000 1.2000
  2 件のコメント
AMZ
AMZ 2022 年 11 月 10 日
Oh thanks Walter.
I forgot to mention the values are present in a Text file say "values.txt", How do I:
  • import the values from the file?
  • How do I then assign to those variables?
Walter Roberson
Walter Roberson 2022 年 11 月 10 日
編集済み: Walter Roberson 2022 年 11 月 10 日
%in your real code you would use a real file name
filename = tempname() + ".txt";
%preparation -- need to write some data into the file in order
%to illustrate reading data from a file
%this section exists only for demonstration purposes.
%in your real code you would skip this section and just assign to the
%filename and then do the fopen and so on
S = ...
"4 6" + newline + ...
"5.2 1.3" + newline + ...
"6.2 8.8" + newline + ...
"4.9 6.9" + newline + ...
"10.2 1.2";
fid = fopen(filename, 'w');
fwrite(fid, S);
fclose(fid);
%now the actual work that you would have in your real file
fid = fopen(filename, 'r');
data = fscanf(fid, '%f %f', [2 inf]) .';
fclose(fid);
data
data = 5×2
4.0000 6.0000 5.2000 1.3000 6.2000 8.8000 4.9000 6.9000 10.2000 1.2000
and if using fscanf() is not a hard requirement being imposed by someone else, then skip the fopen() and so on, and just use
data = readmatrix(filename)
data = 5×2
4.0000 6.0000 5.2000 1.3000 6.2000 8.8000 4.9000 6.9000 10.2000 1.2000

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by