Anon
Anon

Reputation: 5

Load file into MATLAB

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

Upvotes: 0

Views: 100

Answers (1)

Adriaan
Adriaan

Reputation: 18187

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.

Upvotes: 1

Related Questions