use fprinft with an unknown format in matlab - matlab

I would like to save the output of several evals ( don't know the input of those ) in a file. Now I don't know the tpye of those evals They could be arrays or strings or integer or anything, so I can not really write fprinft(fileID, '%s\n', eval(somethingsomething)); since I don't know what the second parameter should be. Is there a way a for me to save those in a file?

You can save the results of the eval in a local variable and check the resulting type with class(v) and use printf accordingly.

I believe you can just save result of eval with fwrite(), why would you use fprintf?

Related

Writing Tables from Matlab into CSV

I have several tables in matlab that and I would like to write all to one .csv file, vertically concatenating. I would like to keep the column names from each table as the top row, and would like to use a loop to write the csv. The ultimate goal is to read the data in to R, but R.matlab did not work well. Suggestions about how to do this?
Alternatively how can I change filenames in a for loop using the iterator?
e.g. along the lines of
for i=1:10
writecsv('mydatai.csv',data(i))
end
So I must have at the end 10 csv files as output.
You can change the filename within the loop by using for sprintf string formatting function, for example:
dlmwrite(sprintf('mydata%i.csv', i), data(i) )
Note that the %i portion of the string is the sprintf formatting operator for an integer, it is just a coincidence that you also decided to name your iterator variable 'i'.
You can append extra data to an existing CSV by using the dlmwrite function, which uses a comma delimiter as the default, and including the '-append' flag.
Another way would be to use
writetable(Table,filename )
and to change file name after every alternation you can use
filename = ['mydata' num2str(i) '.csv']

How to print variable inside function

I'm using RRDs::Simple function and it needs bunch of parameters.
I have placed these parameters in a special variable (parsing, sorting and calculating data from a file) with all quotes, commas and other stuff.
Of course
RRDs::create ($variable);
doesn't work.
I've glanced through all perl special variables and have found nothing.
How to substitute name of variable for the data that contained in that variable?
At least could you tell me with what kind of tools(maybe another special variables) it can be done?
Assuming I'm understanding what you're asking:
You've build the 'create' data in $variable, and are now trying to use RRDs::create to actually do it?
First step is:
print $variable,"\n"; - to see what is actually there. You should be able to use this from the command line, with rrdtool create. (Which needs a filename, timestep, and some valid DS and RRA parameters)
usually, I'll use an array to pass into RRDs::create:
RRDs::create ( "test.rrd", "-s 300",
"DS:name:GAUGE:600:U:U", )
etc.
If $variable contains this information already, then that should be ok. The way to tell what went wrong is:
if ( RRDs::error ) { print RRDs::error,"\n"; }
It's possible that creating the file is the problem, or that your RRD definitions are invalid for some reason. rrdtool create on command line will tell you, as will RRDs::error;

save svm models to file matlab

I have 31 models an I want to save each one in a specific file
this is my matlab function
formatspec='model%d'
for k = 1:length(libsvmFiles)
baseFileName = libsvmFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
[labels train]=libsvmread(fullFileName);
model=svmtrain(labels,train, '-t 2 -h 0');
file=sprintf(formatspec,k);
save file model;
but the problem is only the first file is saved and its name is 'file' tha's mean the value of the variable file is not evaluated
how can I solve this problem ?
As many Matlab functions, save can be used in function form (save(...)) or in command form (save ...). In the command form that you use, all the arguments are interpreted as strings. That means
save file model
is equivalent to
save('file', 'model')
For the second argument that is correct, because you want to refer to the variable with the name "model". For the first argument it is wrong, because you want to refer to the file name contained in the variable file. The correct syntax to use is therefore
save(file, 'model')
You're missing the parens for the save function. The model variable also needs to be listed as a string since you need to tell the save function the name of the variable, not the variable itself. See Matlab's documentation.
save(file, 'model');
Additionally you don't have an end to your for loop shown, which normally would just throw an error -- however later code might cause this loop to instead only run once. Otherwise you should check your libsvmFiles variable as it might be only length 1 or not be an array.

parse a fractional number into matlab from a configuration file

In a matlab program I have an external parameter file that needs to be read in. Like
a = 1/3
b = 'test'
Currently I use textscan to read this file and use str2num to parse the values of a. However, I read that str2num use eval inside, which is undesirable for safety reason: what if someone made a = 'delete something', and then str2num will execute the string as a side effect. str2double does not work for fractional numbers. Is there any better way to parse 1/3 from external file into matlab?
If you are going to parse input that can only be a simple number or a division, the str2double/str2double approach may be sufficient. However if you want to parse input safely in general, I would recommend restricting the input.
For example like so:
rawString= 'dir+3/5'
safeCharacters = ['0':'9' '+-*/\^eEij. '];
if all(ismember(rawString,safeCharacters))
str2num(junkString)
end
Of course this may filter out some potentially good input like: str2num('rand')
Personally, I'd use str2num (which is based on eval if you read the documentation). However, another option is sym. The Symbolic Math toolbox is based on eval as well of course, but it has input validation to avoid the potential dangers you're worried about. It is very robust and simple to use for what you need:
a = '1/3';
a = double(sym(a))
This also handles converting cell arrays of strings to vectors and matrices gracefully:
a={'1/3','1/33','1/333'; ...
'2/3','2/33','2/333'};
a = double(sym(a))
The following unlikely input will return warnings and an error (and not delete a in memory):
b = 'delete a';
a = double(sym(b))
Thus you may want to use a try/catch statement to gracefully handle cases when a user may provide invalid input:
try
Xs = double(sym(X));
catch err
if strcmp(err.id,'MATLAB:UndefinedFunction')
error('YourFunctionName:UnknownInput','Your helpful message here.');
else
rethrow(err);
end
end
You could equally replace the Xs = double(sym(X)); line with a call to str2num.
You can explicitly search for the backslash with strfind.
if ~isempty(strfind(X, '/'))
% then use str2num
else
% use str2double, and if this returns a NaN, then it is a string
end
Or use strtok to split the string using '/' as a token, and use str2double on all resulting elements.

Proper print using fprintf in matlab

So I have the function print_date which goes
fprintf('%d.%d.%d\n, date.day, date.month, date.year)
Which in this case prints out "20.5.1990"
But I want to remove the \n part because Im need to use this function in another. However, when I remove the \n, the output on the print_date becomes, I dont know how to explain. But the
the ">>" at the beginning of the command window becomes:
"20.5.1990>>" instead of "20.5.1990"
How do I fix this?
If you want to use the function print_date in another function, add a return value to print_date. The fprintf writes data to text file or to the console window. If the output string needs to be stored into a variable, use sprintf. You can then display the value of the variable using disp. Here's an example, but I recommend you to read the documentation for more info.
function s=print_date(date)
s=sprintf('%d.%d.%d', date.day, date.month, date.year);
disp(s);
end