Cannot create .txt file in Matlab online

I am trying to create a .txt to put some in some numbers to pull back out later.
My code is:
fileID = fopen('MyFile.txt', 'w');
When I run the code it creates a varable fileID that is shown in the workspace panel (on the lower left of the screen) as a double. But no file is created over in the files panel and when I try to read from that file it then gives an error that the file doesn't exist.

Answers (1)

I am not certain what the problem is. Using fopen only creates the file ID, as you discovewred.
To write the file, you need to do something like this —
fileID = fopen('MyFile.txt', 'w');
A = magic(5)
A = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
fprintf(fileID, '%2d %2d %2d %2d %2d\n', A);
fclose(fileID);
type('MyFile.txt')
17 23 4 10 11 24 5 6 12 18 1 7 13 19 25 8 14 20 21 2 15 16 22 3 9
That should work as well on MATLAB Online.
EDIT — (25 Sep 2023 at 15:18)
Exporting it to your computer requires that you go to MATLAB Drive, check the file name, and then click on ‘Download’. (Added in EDIT.)
.

4 Comments

I copied the text into the actual program once I got to a computer that had it installed. Worked perfectly. So I guess my problem was just the online platform being glitchy.
Well, no, actually. The online platform was not at all glitchy.
The fopen function creates the file identifier, and opens the file for access (reading, writing, &c.). It does nothing else. If you then want to write to the file or read from it, use the file ID to do that, with the appropriate functions, as I did here to write to it, then close the file. I just used the type function to demonstrate that it had been created and written to. I could have used readtable or readmatrix, or textscan, or fscanf to read it.
It wasn't creating a file though. I didn't show it here (though I realize now I should have) but I did have a couple fprintf lines to write info to the .txt fine and nothing was happening. There was no file, and even when I created 1 manually and uploaded it, it still wasn't being written to.
I literally changed nothing and pasted into the program and it worked, I got a file and stuff wrote to it. The only difference was the online platform vs the full program.
Regardless, now that I have access to the full program my problem seems to be resolved. I appreciate you giving some more explanation and trying to help.
Did you try your fprintf calls with my code (using them instead of my fprintf call)?
Can you try them here? (Use the Code button ‘Insert a line of code’ to format it as code and then run the code by clicking on the green Run arrow in the top toolstrip.)
I have never had any problems with MATLAB Online (that I did not cause myself).

Sign in to comment.

Asked:

on 24 Sep 2023

Commented:

on 27 Sep 2023

Community Treasure Hunt

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

Start Hunting!