从 txt 文件 MATLAB 读取 N 个整数
Read N integers from txt file MATLAB
我正在尝试使用 MATLAB
编写一个脚本,该脚本从 txt
文件(其中 100*3
元素写入单个列)中读取。我想一次读取它们 100
个元素并应用拟合指数函数。这是我写的:
defaultPath = 'my/default/path/';
prompt = 'file name? ';
fileName = input(prompt,'s');
fullPath = strcat(defaultPath,fileName);
fileID = fopen(fullPath);
for h = 1:3
buff = textscan(fileID, '%d', 100);
y=buff';
x = zeros([100, 1]);
for j = 1:100
x(j,1) = j;
end
f = fit(x,y,'exp1');
plot(f,x,y);
end
但它给了我这个错误:
X and Y must have the same number of rows.
您的主要问题可能是 fit
的两个输入向量的形状不同:一个是 size
[100 1]
,另一个是 [1 100]
,即一个是一个列向量,另一个是一行。我建议这样做:
defaultPath = 'my/default/path/';
prompt = 'file name? ';
fileName = input(prompt,'s');
fullPath = strcat(defaultPath,fileName);
fileID = fopen(fullPath);
for h = 1:3
buff = textscan(fileID, '%d', 100);
y=buff{1}';
x = 1:length(y);
f = fit(x,y,'exp1');
figure; %open new window for plotting each slice of the data
plot(f,x,y);
end
fclose(fileID);
请注意,我在绘图之前添加了一个 figure
调用,以便将 3 组数据绘制在不同的图形上(否则默认行为将是每个 plot
覆盖前一个在同一个 figure
.
我还更改了 x
的定义,使其明确匹配 y
的长度,这将防止一些错误,以防读取出现问题并且 y
有非平凡的长度。无论如何,最好避免幻数,并尽可能根据其他数来定义所有内容。
您可以按如下方式使用csvread:
f = csvread(STRING_OF_FILE_NAME);
f 将是一个包含数据的矩阵。
我正在尝试使用 MATLAB
编写一个脚本,该脚本从 txt
文件(其中 100*3
元素写入单个列)中读取。我想一次读取它们 100
个元素并应用拟合指数函数。这是我写的:
defaultPath = 'my/default/path/';
prompt = 'file name? ';
fileName = input(prompt,'s');
fullPath = strcat(defaultPath,fileName);
fileID = fopen(fullPath);
for h = 1:3
buff = textscan(fileID, '%d', 100);
y=buff';
x = zeros([100, 1]);
for j = 1:100
x(j,1) = j;
end
f = fit(x,y,'exp1');
plot(f,x,y);
end
但它给了我这个错误:
X and Y must have the same number of rows.
您的主要问题可能是 fit
的两个输入向量的形状不同:一个是 size
[100 1]
,另一个是 [1 100]
,即一个是一个列向量,另一个是一行。我建议这样做:
defaultPath = 'my/default/path/';
prompt = 'file name? ';
fileName = input(prompt,'s');
fullPath = strcat(defaultPath,fileName);
fileID = fopen(fullPath);
for h = 1:3
buff = textscan(fileID, '%d', 100);
y=buff{1}';
x = 1:length(y);
f = fit(x,y,'exp1');
figure; %open new window for plotting each slice of the data
plot(f,x,y);
end
fclose(fileID);
请注意,我在绘图之前添加了一个 figure
调用,以便将 3 组数据绘制在不同的图形上(否则默认行为将是每个 plot
覆盖前一个在同一个 figure
.
我还更改了 x
的定义,使其明确匹配 y
的长度,这将防止一些错误,以防读取出现问题并且 y
有非平凡的长度。无论如何,最好避免幻数,并尽可能根据其他数来定义所有内容。
您可以按如下方式使用csvread:
f = csvread(STRING_OF_FILE_NAME);
f 将是一个包含数据的矩阵。