read a text file from desktop and add first 10 numbers in matlab & display the sum of first 10 numbers in matlab without using function in matlab

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

  1. Specify the file path of the text file located on your desktop:
main.m
file_path = 'C:\Users\YourUsername\Desktop\filename.txt'; 
59 chars
2 lines

Replace YourUsername with your actual username and filename.txt with the name of your file.

  1. Open the file in read mode:
main.m
fileID = fopen(file_path, 'r');
32 chars
2 lines
  1. Read the first 10 numbers from the file:
main.m
numbers = fscanf(fileID, '%f', 10);
36 chars
2 lines

This will read the first 10 numbers as a column vector.

  1. Close the file:
main.m
fclose(fileID);
16 chars
2 lines
  1. Calculate the sum of the first 10 numbers:
main.m
sum_of_numbers = sum(numbers);
31 chars
2 lines
  1. Display the sum:
main.m
disp(sum_of_numbers);
22 chars
2 lines

Here's the complete code:

main.m
file_path = 'C:\Users\YourUsername\Desktop\filename.txt';
fileID = fopen(file_path, 'r');
numbers = fscanf(fileID, '%f', 10);
fclose(fileID);
sum_of_numbers = sum(numbers);
disp(sum_of_numbers);
195 chars
7 lines

Please note that you need to replace YourUsername with your actual username and filename.txt with the name of your file. Also, make sure the file contains at least 10 numbers in the desired format.

Make sure the path to the file is correct and the file exists in that location.

related categories

gistlibby LogSnag