read a text file from desktop and add first 10 numbers in matlab & display the sum of first 10 numbers in matlab, store each result in a array in matlab

To read a text file from the desktop in MATLAB, you can use the textread or readtable functions. Here's an example using the textread function:

main.m
file_path = 'C:\Users\YourUsername\Desktop\sample.txt'; % Update the file path with your username and file name

data = textread(file_path, '%f'); % Read the file data as numbers

first_10_numbers = data(1:10); % Extract the first 10 numbers

sum_of_first_10_numbers = sum(first_10_numbers); % Calculate the sum of the first 10 numbers

result_array = [];

for i = 1:10
    result_array(i) = sum(data(1:i)); % Calculate the sum up to i-th number and store in the result array
end

result_array % Display the result array in the MATLAB command window
550 chars
16 lines

Make sure to replace 'C:\Users\YourUsername\Desktop\sample.txt' with the actual path of your text file.

Note: If your text file contains non-numeric values or has a different format, you may need to update the code accordingly.

related categories

gistlibby LogSnag