Using the function command to open a .txt file

3 views (last 30 days)
The instruction on our homework was;
First Part
Accept the values n and m ( n - number of floors and m - number of apartments on each floor) the from the user and define appropriate size array to hold the number of mail items each resident has. Fill the array with random integer number in the range of 0 to 9.
Second part (I am currently stuck)
Write a function which will read the above file and determine the total mail items in the mailbox. Make sure to close the file before you leave the function. Call the function and print the result.
I think I am misunderstanding how the function command works, here is what I have;
m=input('Number of floors of the building: \n ');
n=input('Number of apartments per floor: \n');
array_mail=randi([0 9],n,m);
ave=mean(array_mail,'all');
fprintf('The average mail recieved by residents is: %4.0f\n',ave)
writematrix(array_mail,'perez_jethro_mailbox.txt')
function total_mail=AllMail('perez_jethro_mailbox.txt')
q = dlmread('perez_jethro_mailbox.txt')
total_mail = sum(q);
end
thanks for all the help

Accepted Answer

Walter Roberson
Walter Roberson on 1 Dec 2020
function total_mail=AllMail(filename)
q = dlmread(filename)
and somewhere you would need to invoke the function with a file name such as
AllMail('perez_jethro_mailbox.txt')
  2 Comments
Jethro Perez
Jethro Perez on 1 Dec 2020
function total_mail=AllMail(filename)
q = dlmread(filename)
So what did this line achieve?
Create a function called total_mail?
Walter Roberson
Walter Roberson on 1 Dec 2020
Create a function named AllMail that accepts a single parameter. Inside the function, whatever the value is that was passed as the single parameter will be known under the name filename . Everywhere in the function body that filename is used, the value that is passed in to the function will be substituted.
The function is expected to return a single array, and whatever is assigned to the variable total_mail is what will be returned.
You still need the line
total_mail = sum(q);
I just left it out because I was not changing it.

Sign in to comment.

More Answers (1)

Jethro Perez
Jethro Perez on 1 Dec 2020
Yes thank you so much for the help. I had to read that a couple of times over but I think I have a better grasp of it.

Categories

Find more on Numeric Types in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!