MATLAB Saving Figure Invalid Filename Error - matlab

I am writing a program to plot graphs in a loop and I want to save each graph that comes out as a .jpg file with a variation of the file name. Here is my code for saving the graphs:
filename = strcat('WI_Pollutants_', D(i,6), '_200706_O3');
saveas(gcf, filename, 'jpg');
The saved file should come out as the following with D(i,6) changing each iteration of the loop.
WI_Pollutants_003-0010_200706_O3.jpg
However, I'm running an error: (Maybe it has to due with saveas wanting a string only?)
Error using saveas (line 81)
Invalid filename.

saveas only accepts characters as the filename. But when filename was created, strcat made it a cell array. Therefore, the filename needs to be converted to a character array.
filename = char(strcat('WI_Pollutants_', D(i,6), '_200706_O3'));
saveas(gcf, filename, 'jpg');
This solves the problem.

I think your D{i,6} is ending up wrapped up as an array, from this line:
D{i,6} = [num2str(D{i,6}) '-' num2str(D{i,7})];
To solve this, just removing the []'s
D{i,6} = num2str(D{i,6}) '-' num2str(D{i,7});
I think what happened is your D{i,6}=['someString'], and concatinating added in the []'s that werent' desired.
As a check, if something like this happens again, just fprintf(filename) right before use, and look at what comes out. I suspect you'll find the issue there. You can always remove the print statement later on.

Related

Removing quotes that seem to be nonexistent in MatLab

I have an application that translates the .csv files I currently have into the correct format I need. But, the files I that I do have seem to have '"' double quotes around them, as seen in this image, which will not work with the program. As a result, I'm using this command to remove them:
for m = 1:currentsize(1)
for n = 1:currentsize(2)
replacement{m,n} = strrep(current{m,n}, '"', '');
end
end
I'm not entirely sure that this works though, as it spits this back at me as it runs:
Warning: Inputs must be character arrays or cell arrays of strings.
When I open the file in matlab, it seems to only have the single quotes around it, which is normal for any other file. However, when I open it in notepad++, it seems to have '"' double quotes around everything. Is there a way to remove these double quotes in any other way? My code doesn't seem to do anything as seen here:
After using xlswrite to write the replacement cell-array to a .csv file, one appears corrupted. Any idea why?
So, my questions are:
Is there any way to remove the quotes in a more efficient manner or without rewriting to a csv?
and
What exactly is causing the corruption in the xlswrite function? The variable replacement seems perfectly normal.
Thanks in advance!
Regarding the "corrupted" file. That's not a corrupted file, that's an xls file (not xlsx). You could verify this opening the text file in a hex editor to compare the signature. This happens when you chose no file extension or ask excel to write a file which can't be encoded into csv. I assume it's some character which causes the problems, try to isolate the critical line writing only parts of the cell.
Regarding your warning, not having the actual input I could only guess what's wrong. Again, I can only give some advices to debug the problem yourself. Run this code:
lastwarn('')
for m = 1:currentsize(1)
for n = 1:currentsize(2)
replacement{m,n} = strrep(current{m,n}, '"', '');
if ~isempty(lastwarn)
keyboard
lastwarn('')
end
end
end
This will launch the debugger when a warning is raised, allowing you to check the content of current{m,n}
It is mentionned in the documentation of strrep that :
The strrep function does not find empty strings for replacement. That is, when origStr and oldSubstr both contain the empty string (''), strrep does not replace '' with the contents of newSubstr.
You can use this user function substr like this :
for m = 1:currentsize(1)
for n = 1:currentsize(2)
replacement{m,n} = substr(current{m,n}, 2, -1);
end
end
Please use xlswrite function like this :
[status,message] = xlswrite(___)
and check the status if it is zero, that means the function did not succeed and an error message is generated in message as string.

Index out of bounds after reading a text file

I have the following simple code, and I tried to use one of the indices from the .txt file. The index that I want is at (4,1) while the size of my matrix in the .txt file is (8,4). When I run the code, MATLAB give me the following error;
Attempted to access q(4,1); index out of
bounds because size(q)=[1,601]
Can someone help me understand why I receive the error and how to fix it?
Here is the code:
q = fileread('sv11edit.txt');
toe = q(4,1)
The answer will depend on the format of the file sv11edit.txt. However, fileread returns a string of characters. In this case, it gives you a string that is 601 characters long. You receive an error because you assume that q is 8 by 4, but this is not the case.
Check what is being stored in q before you try anything like the second line of your code. The function load may be a better alternative to fileread.

Matlab - Error using save Cannot create '_' because '_____' does not exist

I have some data in a cell array,
data2={[50,1;49,1;26,1];...
[36,2;12,2;37,2;24,2;47.3,2];}
and names in another cell array,
names2={'xxx/01-ab-07c-0fD3/0';'xxx/01-ab-07s-0fD3/6';}
I want to extract a subset of the data,
data2_subset=data2{1,:}(:,1);
then a temporary file name,
tempname2=char(names2(2));
an save the subset to a text file with
save (tempname2, 'data2_subset', '-ASCII');
But I get this error message: _
Error using save
Cannot create '6' because 'xxx/01-ab-07s-0fD3' does not exist.
To try to understand what is happening, I created a mock dataset with simpler names:
names={'12-05';'14-03'};
data={[50,1;29,1;25,1];[35,2;22,2;16,2;38,2];[40,3;32,3;10,3;44,3;43,3];};
data_subset=data{1,:}(:,1);
tempname=char(names(2));
save (tempname, 'data_subset', '-ASCII');
in which case the save command works properly.
Unfortunately I still do not understand what the problem is in the first case. Any suggestions as to what is happening, and of possible solutions?
MATLAB is interpreting the the forward slashes (/) as directory separators and 6 as the intended file name (your second example doesn't have this slash problem).
Since the relative directory tree xxx/01-ab-07s-0fD3/ doesn't exist, MATLAB can't create the file.
To solve the problem, you can either create the directories beforehand using mkdir():
>> pieces = strsplit(tempname2,'/');
>> mkdir(pieces{1:2});
>> save(tempname2, 'data2_subset', '-ASCII');
or replace the / with some other benign symbol like _:
>> tempname3= strrep(tempname2,'/','_');
>> save (tempname3, 'data2_subset', '-ASCII');
(which works for me).

Using datestr(now) with save

The code is:
filename = sprintf('michael%s.bat',datestr(now));
...
save (filename,vec)
vec is a vector
I'm getting this error:
Error using save
Argument must contain a string.
Error in sumfnc (line 13)
save (filename,vec)
I'm unsure on how filename is not a string.
The problem is not filename, it is vec. With the functional usage of save, you need to do:
save(filename,'vec')
However, since filename will contain a space, you will also need to modify filename. Try:
save(strrep(filename,' ','_'),'vec')
to replace spaces with _.

MATLAB: How do you insert a line of text at the beginning of a file?

I have a file full of ascii data. How would I append a string to the first line of the file? I cannot find that sort of functionality using fopen (it seems to only append at the end and nothing else.)
The following is a pure MATLAB solution:
% write first line
dlmwrite('output.txt', 'string 1st line', 'delimiter', '')
% append rest of file
dlmwrite('output.txt', fileread('input.txt'), '-append', 'delimiter', '')
% overwrite on original file
movefile('output.txt', 'input.txt')
Option 1:
I would suggest calling some system commands from within MATLAB. One possibility on Windows is to write your new line of text to its own file and then use the DOS for command to concatenate the two files. Here's what the call would look like in MATLAB:
!for %f in ("file1.txt", "file2.txt") do type "%f" >> "new.txt"
I used the ! (bang) operator to invoke the command from within MATLAB. The command above sequentially pipes the contents of "file1.txt" and "file2.txt" to the file "new.txt". Keep in mind that you will probably have to end the first file with a new line character to get things to append correctly.
Another alternative to the above command would be:
!for %f in ("file2.txt") do type "%f" >> "file1.txt"
which appends the contents of "file2.txt" to "file1.txt", resulting in "file1.txt" containing the concatenated text instead of creating a new file.
If you have your file names in strings, you can create the command as a string and use the SYSTEM command instead of the ! operator. For example:
a = 'file1.txt';
b = 'file2.txt';
system(['for %f in ("' b '") do type "%f" >> "' a '"']);
Option 2:
One MATLAB only solution, in addition to Amro's, is:
dlmwrite('file.txt',['first line' 13 10 fileread('file.txt')],'delimiter','');
This uses FILEREAD to read the text file contents into a string, concatenates the new line you want to add (along with the ASCII codes for a carriage return and a line feed/new line), then overwrites the original file using DLMWRITE.
I get the feeling Option #1 might perform faster than this pure MATLAB solution for huge text files, but I don't know that for sure. ;)
How about using the frewind(fid) function to take the pointer to the beginning of the file?
I had a similar requirement and tried frewind() followed by the necessary fprintf() statement.
But, warning: It will overwrite on whichever is the 1st line. Since in my case, I was the one writing the file, I put a dummy data at the starting of the file and then at the end, let that be overwritten after the operations specified above.
BTW, even I am facing one problem with this solution, that, depending on the length(/size) of the dummy data and actual data, the program either leaves part of the dummy data on the same line, or bring my new data to the 2nd line..
Any tip in this regards is highly appreciated.