将文件加载到MATLAB中
我希望用户键入文件的名称和文件,而不是询问用户坐标点的数量,然后键入它们。
该文件看起来像这样:
1 2
4 6
7 3
这是获取用户输入的脚本的部分。如何向用户询问文件的名称并将其用作输入?
disp('This program performs a least-squares fit of an ');
disp('input data set to a straight line.');
n_points = input('Enter the number of input [x y] points: ');
for ii = 1:n_points
temp = input('Enter [x y] pair: ');
x(ii) = temp(1);
y(ii) = temp(2);
end
Instead of my script asking the user the number of coordinate points and then to type them, I wanted the user to type the name of a file and the file to be read.
The file looks like this:
1 2
4 6
7 3
This is the piece of the script that gets the user input. How can I ask the user the name of the file and use it as input?
disp('This program performs a least-squares fit of an ');
disp('input data set to a straight line.');
n_points = input('Enter the number of input [x y] points: ');
for ii = 1:n_points
temp = input('Enter [x y] pair: ');
x(ii) = temp(1);
y(ii) = temp(2);
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
uigetfile(uigetfile()您的操作系统文件浏览器。
困难的方法:如果您希望用户手动键入文件名,则可以使用
input
:for 循环的侧面注释,在中>循环迭代的数量已知,在您的情况下
n_points
。而不是在循环中生长x
y y , preallocate 他们。这在很小的阵列上并没有太大的不同,但是如果您有成千上万的迭代,您会注意到大量减速。因此,在循环之前,调用x = zeros(n_points,1)
,对于y
相同。最好是创建coordinates = zeros(n_points,2)
并保存坐标(ii,:) = temp
在循环中,保持坐标并减少金额变量。You can use
uigetfile()
, which opens your OS's file browser.The hard way: if you want the user to manually type the file name you can use
input
:Side note on your
for
loop, in afor
loop the number of iterations is know, in your casen_points
. Rather than growingx
andy
within the loop, preallocate them. This doesn't make much of a difference on very small arrays, but if you've got tens of thousands of iterations, you'll notice a significant slow-down. Thus, callx = zeros(n_points, 1)
, same fory
, before the loop. Better even would be to createcoordinates = zeros(n_points, 2)
and savecoordinates(ii,:) = temp
within the loop, keeping your coordinates together and reducing the amount of variables.