I have a .txt file that looks like this
I am: 25.787
You may be: 55.88
He should not be: 5576.5454
She is not going to be: 12.556
I am: 56.545
You may be: 13.987
He should not be: 6.455
She is not going to be: 12.67
...
I want to read this file and construct a matrix which is in the following form:
25.787 55.88 5576.5454 12.556
56.545 13.987 6.455 12.67
...
I looked at fscanf documentation and tried very hard but I can not understand it. Could someone please explain how I should construct my matrix?
In almost any case of data import importdata function is a mighty tool.
grouplength = 4;
DATA = importdata('myData.txt',':')
output = reshape(DATA.data,grouplength,[]).'
25.7870000000000 55.8800000000000 5576.54540000000 12.5560000000000
56.5450000000000 13.9870000000000 6.45500000000000 12.6700000000000
localfunctions returns function handles to all the local functions in an m-file. However, this doesn't work in a package. For example, the following code saved as 'a.m' runs fine:
function fs = a()
fs = localfunctions;
end
function babo()
end
function hidden()
end
Called from MATLAB console:
>> a()
ans =
#babo
#hidden
But when it is inside a package as '+aaa/b.m', I get nothing:
>> aaa.b()
ans =
{}
I don't think this behavior is well documented. How do I overcome this?
I need to use localfunctions to unit test some functions within the package and I don't want to keep it outside of the package just because of this.
One solution would be to import the package before calling localfunctions:
+mypkg/mytest.m
function f = mytest()
import mypkg.*
f = localfunctions;
end
function foo()
end
function bar()
end
When called:
>> f = mypkg.mytest()
f =
#foo
#bar
>> functions(f{1})
ans =
function: 'foo'
type: 'scopedfunction'
file: 'C:\Users\Amro\Desktop\+mypkg\mytest.m'
parentage: {'foo' 'mytest'}
There is a bug in R2013b and R2014a where localfunctions does not respect the package of the file containing the local functions. This bug has been reported to The MathWorks for fixing in a future release.
Until then, Amro's workaround is the best option.
EDIT: This has been fixed in release R2014b.
I want to use mpiMatlab for my algorithm,i have problem in INSTALLING AND RUNNING of it.
According to this link can any one help me:
http://www.ll.mit.edu/mission/isr/matlabmpi/matlabmpi.html
when i wrote this command in matlab:
eval( MPI_Run( MPI_cc('xbasic'), 2,machines) );
It gives me this error:
??? Undefined function or
method 'MPI_cc' for input
arguments of type 'char'.
Error in ==> Untitled at 1
eval( MPI_Run(
MPI_cc('xbasic'), 2,machines)
);
The error messages suggests that the source code folder is not defined in your MATLABPATH.
Try
which MPI_cc
To see if you can see the code.
Then try to walk before you run.
Does this work?
eval( MPI_Run('xbasic', 2,machines) );
Next does this work?
MPI_cc('xbasic');
Once all these steps are working then you can try your original code.
eval( MPI_Run( MPI_cc('xbasic'), 2,machines) );
I created an anonymous function inside a script and I can't get MATLAB to run the fminsearch? Here's an what I have so far:
V=x(1);
f=x(2);
q=#(x) (pi.*D.*L)./(1000.*V.*f);
fminsearch(#q,x);
The variables D and L are defined, but MATLAB gives me the following error:
Error: File: Testing.m Line: 51 Column: 17
"q" was previously used as a variable, conflicting with its use here as the name of a function or command.
See "How MATLAB Recognizes Command Syntax" in the MATLAB documentation for details.
q is not mentioned before this command. What am I doing wrong?
Another thing that could solve my problem is to get my script to write a function file, but how to do that?
Remove the second #:
V=x(1);
f=x(2);
q=#(x) (pi.*D.*L)./(1000.*V.*f);
fminsearch(q,x);
q is a function handle. fminsearch expects a function handle. You can create a function handle out of a function using an # (e.g. #min), but you don't need to do that here.
You can also write the anonymous function inline with the search command:
V=x(1);
f=x(2);
fminsearch(#(x) (pi.*D.*L)./(1000.*V.*f),x);
UPDATE (credits to #wakjah)
For your code to do anything sensible, you should use the argument x of the anonymous function:
x0 = [initialV, initialF];
fminsearch(#(x) (pi.*D.*L)./(1000.*x(1).*x(2)), x0);
#function creates a function handle for an existing function.
q = #(x) whatever... creates a function handle called q.
But, you can't create a function handle for a function handle, only for a function.
See this:
>> fones = #ones
fones =
#ones
>> ffones = #fones
Error: "fones" was previously used as a
variable,
conflicting with its use here as the name
of a function or command.
See MATLAB Programming, "How MATLAB
Recognizes Function Calls That Use
Command Syntax" for details.
In Matlab, a function handle is a kind of a pointer to a function and is distinct from a function (unlike in some other languages where the a function identifier can be passed and stored as any other variable).
It's important to note that calling a function and a function handle results in the same behaviour. Except for the case where the identifier is used without any parentheses following it:
>> ones
ans =
1
>> fones
fones =
#ones
>> ones(2)
ans =
1 1
1 1
>> fones(2)
ans =
1 1
1 1
I am using
fid = fopen('fgfg.txt');
to open a file.
Sometimes an error occurs before I manage to close the file. I can't do anything with that file until I close Matlab.
How can I close a file if an error occurs?
First of all, you can use the command
fclose all
Secondly, you can use try-catch blocks and close your file handles
try
f = fopen('myfile.txt','r')
% do something
fclose(f);
catch me
fclose(f);
rethrow(me);
end
There is a third approach, which is much better. Matlab is now an object-oriented language with garbage collector. You can define a wrapper object that will take care of its lifecycle automatically.
Since it is possible in Matlab to call object methods both in this way:
myObj.method()
and in that way:
method(myObj)
You can define a class that mimics all of the relevant file command, and encapsulates the lifecycle.
classdef safefopen < handle
properties(Access=private)
fid;
end
methods(Access=public)
function this = safefopen(fileName,varargin)
this.fid = fopen(fileName,varargin{:});
end
function fwrite(this,varargin)
fwrite(this.fid,varargin{:});
end
function fprintf(this,varargin)
fprintf(this.fid,varargin{:});
end
function delete(this)
fclose(this.fid);
end
end
end
The delete operator is called automatically by Matlab. (There are more functions that you will need to wrap, (fread, fseek, etc..)).
So now you have safe handles that automatically close the file whether you lost scope of it or an error happened.
Use it like this:
f = safefopen('myFile.txt','wt')
fprintf(f,'Hello world!');
And no need to close.
Edit:
I just thought about wrapping fclose() to do nothing. It might be useful for backward compatibility - for old functions that use file ids.
Edit(2): Following #AndrewJanke good comment, I would like to improve the delete method by throwing errors on fclose()
function delete(this)
[msg,errorId] = fclose(this.fid);
if errorId~=0
throw(MException('safefopen:ErrorInIO',msg));
end
end
You can try a very neat "function" added by ML called onCleanup. Loren Shure had a complete writeup on it when it was added. It's a class that you instantiate with your cleanup code, then it executes when it goes out of scope - i.e. when it errors, or the function ends. Makes the code very clean. This is a generic version of the class that Andrey had above. (BTW, for complex tasks like hitting external data sources, custom classes are definitely the way to go.)
from the help:
function fileOpenSafely(fileName)
fid = fopen(fileName, 'w');
c = onCleanup(#()fclose(fid));
functionThatMayError(fid);
end % c executes fclose(fid) here
Basically, you give it a function handle (in this case #()fclose(fid))that it runs when it goes out of scope.
Your cleanup code is executed either when an error is thrown OR when it exits normally, because you exit fileOpenSafely and c goes out of scope.
No try/catch or conditional code necessary.
Andrey's solution above is indeed the best approach to this problem. I just wanted to add that throwing an exception in method delete() might be problematic, if you deal with arrays of safefopen objects. During destruction of such an array, MATLAB will call delete() on each array element and, if any delete() throws, then you might end up with leftover open file handles. If you really need to know whether something went wrong during destruction then issuing a warning would be a better option IMHO.
For those that feel lazy to write all the forwarding methods to every MATLAB builtin that uses file handles, you may consider the simple alternative of overloading method subsref for class safefopen:
methods(Access=public)
function varargout = subsref(this, s)
switch s(1).type
case '.'
if numel(s) > 1,
feval(s(1).subs, this.fid, s(2).subs{:});
else
feval(s(1).subs, this.fid);
end
% We ignore outputs, but see below for an ugly solution to this
varargout = {};
otherwise
varargout{1} = builtin('subsref', this, s);
end
end
end
This alternative uses the somewhat ugly feval, but has the advantage of working even if the MATLAB guys (or yourself) decide to add new functions that involve file handles, or if the number/order of the input arguments to a given function change. If you decide to go for the subsref alternative then you should use class safefopen like this:
myFile = safefopen('myfile.txt', 'w');
myFile.fprintf('Hello World!');
EDIT: A disadvantage of the subsref solution is that it disregards all output arguments. If you need the output arguments then you will have to introduce some more ugliness:
methods(Access=public)
function varargout = subsref(this, s)
if nargout > 0,
lhs = 'varargout{%d} ';
lhs = repmat(lhs, 1, nargout);
lhs = ['[' sprintf(lhs, 1:nargout) ']='];
else
lhs = '';
end
switch s(1).type
case '.'
if numel(s) > 1,
eval(...
sprintf(...
'%sfeval(''%s'', this.fid, s(2).subs{:});', ...
lhs, s(1).subs) ...
);
else
eval(...
sprintf('%sfeval(''%s'', this.fid);', ...
lhs, s(1).subs) ...
);
end
otherwise
varargout{1} = builtin('subsref', this, s);
end
end
end
And then you could do things like:
myFile = safefopen('myfile.txt', 'w');
count = myFile.fprintf('Hello World!');
[filename,permission,machineformat,encoding] = myFile.fopen();
fids=fopen('all');
fclose(fids);
%assuming that you want to close all open filehandles