read a text file from desktop and add first 10 numbers in matlab

To read a text file from the desktop and add the first 10 numbers in MATLAB, you can follow these steps:

  1. Use the uigetfile function to open a file dialog box and select the text file from your desktop:
main.m
[file, path] = uigetfile('*.txt', 'Select a text file');
57 chars
2 lines
  1. Use the fullfile function to concatenate the path and file name:
main.m
fullFileName = fullfile(path, file);
37 chars
2 lines
  1. Use the fopen function to open the text file for reading:
main.m
fileID = fopen(fullFileName, 'r');
35 chars
2 lines
  1. Use the fscanf function to read the numbers from the text file:
main.m
numbers = fscanf(fileID, '%f', 10);
36 chars
2 lines
  1. Finally, close the file using the fclose function:
main.m
fclose(fileID);
16 chars
2 lines

Here is the complete code:

main.m
[file, path] = uigetfile('*.txt', 'Select a text file');
fullFileName = fullfile(path, file);
fileID = fopen(fullFileName, 'r');
numbers = fscanf(fileID, '%f', 10);
fclose(fileID);
181 chars
6 lines

Now, the variable numbers will store the first 10 numbers from the text file.

related categories

gistlibby LogSnag