将文件加载到MATLAB中

发布于 2025-02-08 19:27:54 字数 438 浏览 2 评论 0原文

我希望用户键入文件的名称和文件,而不是询问用户坐标点的数量,然后键入它们。

该文件看起来像这样:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情话墙 2025-02-15 19:27:54

您可以使用 uigetfile(uigetfile()您的操作系统文件浏览器。

困难的方法:如果您希望用户手动键入文件名,则可以使用input

file_name = input('Please type the file name', "s");

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:

file_name = input('Please type the file name', "s");

Side note on your for loop, in a for loop the number of iterations is know, in your case n_points. Rather than growing x and y 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, call x = zeros(n_points, 1), same for y, before the loop. Better even would be to create coordinates = zeros(n_points, 2) and save coordinates(ii,:) = temp within the loop, keeping your coordinates together and reducing the amount of variables.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文