Matlab: display full error path - matlab

Consider the following foo.m file:
try
disp(r3)
catch ME
disp(getReport(ME))
end
When I run it with:
matlab -nodisplay -nodesktop -nosplash -nojvm -wait -r "run('foo.m')"
I get:
Undefined function or variable 'r3'.
Error in foo (line 2)
disp(r3)
Error in run (line 96)
evalin('caller', [script ';']);
I was wondering if it is possible to display the full path of those files that are referenced in the errors. I know I can use which and, for instance, get:
ยป which run
C:\prog-lang\matlab\toolbox\matlab\lang\run.m
But I would like the errors to be directly displayed like
Error in C:\prog-lang\matlab\toolbox\matlab\lang\run.m (line 96)
rather than
Error in run (line 96)

One option is simply to hack the error report that is returned by getReport, for example using this function to search and replace each instance of "foo" with the full path to the file -
function msg = getReportFull(e)
stack = dbstack();
stack(1) = [];
msg = getReport(e);
for i = 1:length(stack)
fname = stack(i).name;
fpath = which(stack(i).file);
msg = strrep(msg, ['>' fname '<'], ['>' fpath '<']);
end
end
Then with the following code in "foo.m" -
try
disp(r3);
catch e
disp(getReportFull(e));
end
you will observe this error -
>> run('foo.m')
Undefined function or variable 'r3'.
Error in C:\foo.m (line 2)
disp(r3);
Error in C:\Program Files\MATLAB\R2012b\toolbox\matlab\lang\run.m (line 64)
evalin('caller', [script ';']);
This is absolutely an untested hack, and I make no guarantees that it won't break at a really inopportune moment.

Related

Cannot create output file with saveas

i wrote that code
clear all;
clc;
addpath('C:\Users\John\Documents\MATLAB\code for yannis\anger(W)\');
h1 = dir('C:\Users\John\Documents\MATLAB\code for yannis\anger(W)\');
for i=3:numel(h1)
%disp(h1(i,1).name);
%disp(k);
three(h1(i,1).name);
end
and the three function is
function three(filename)
%disp(filename);
q = char(39);
filename = strcat(q,filename,q)
%disp(filename);
load(filename);
And i get that error:
Error using load
Unable to read file '03a01WaM.mat': No such file or directory.
Error in three (line 7)
load(filename);
Error in run_three (line 13)
three(h1(i,1).name);
i also wrote exist('03a01WaM.mat') and the function return 2
Does anyone has an idea, what am i doing wrong?
There are multiple issues with your code.
addpath is simply unnessecary.
You are using relative path, but not cd. You have to use the full path to access the files.
You are adding a apostrophe to the filename.
Correct code would be:
directory='C:\Users\John\Documents\MATLAB\code for yannis\anger(W)\'; %'
h1 = dir(directory);
for i=3:numel(h1)
filename=fullfile(directory,h1(i,1).name);
load(filename);
end

matlab - suppress error message backtrace

I try to check if input argument is of specific type and throw error message like:
function test(input)
if ~ischar(input)
error('%s is invalid input type.', class(input));
end
end
But Matlab shows error message with backtrace-information:
>> test(1)
Error using test (line 3)
double is invalid input type.
How can I turn off the line Error using test (line 3)?
I'm looking for something similar to off backtrace with warning: warning off backtrace;.
I'm not sure you can. The closest I got was by defining my own error structure:
testerr.message = 'test';
testerr.identifier = '';
testerr.stack.file = '';
testerr.stack.name = 'Test Thing';
testerr.stack.line = 1;
error(testerr)
Which returns:
Error using Test Thing
test
As long as you keep the file field blank it will not display the line specified in the stack.
One potential workaround could be a combination of fprintf and return, courtesy of Undocumented MATLAB:
function test(input)
if ~ischar(input)
fprintf(2, '%s is invalid input type.\n', class(input));
return
end
end
Depending on where this check resides in your real function you might need to get creative with how it exits, since return only kicks you back to the invoking function. Probably have it output a True/False flag?

Running Matlab batch job on HPC cluster

I am trying to get Matlab to execute a number of scripts as individual batch jobs. Each script loads some data from excel sheets and implements a neural network. The neural network uses parfor loops internally for parameter tuning.
When I run the batch job on my local machine it works fine. My Matlab code looks like
job1 = batch('Historical1Step',...
'Profile', 'local',...
'Matlabpool', 3,...
'CaptureDiary',true,...
'CurrentDirectory', '.');
try
job1Results = fetchOutputs(job1);
catch err
delete(job1);
rethrow(err);
end
delete(job1);
and the diary output I get is
--- Start Diary ---
Analysing data for stock BAX
num_its =
2
100%[============================
100%[===================================================]
--- End Diary ---
However, when I change from the 'local' config to my server config I get
--- Start Diary ---
--- End Diary ---
Error using parallel.Job/fetchOutputs (line 869)
An error occurred during execution of Task with ID 1.
Error in SOExample (line 14)
job1Results = fetchOutputs(job1);
Caused by:
Index exceeds matrix dimensions.
I am assuming the problem is something to do with the visibility of my functions/data on the workers, but I have tried every combination of the 'FileDependencies' and 'PathDependencies' options I can think of within the batch function to no avail.
Any help would be much appreciated, and apologies in advance if I have done something monumentally stupid without realising it!
EDIT-
The error stack is as follows:
Index exceeds matrix dimensions.
Error in Historical1Step (line 13)
Error in parallel.internal.cluster/executeScript (line 22)
eval(['iClearAndSetCallerWorkspace(workspaceIn);' scriptName]);
Error in parallel.internal.evaluator/evaluateWithNoErrors (line 14)
[out{1:nOut}] = feval(fcn, args{:});
Error in parallel.internal.evaluator/CJSStreamingEvaluator/evaluate (line 31)
[out, errOut] = parallel.internal.evaluator.evaluateWithNoErrors( fcn, nOut, args );
Error in dctEvaluateTask>iEvaluateTask/nEvaluateTask (line 281)
[output, errOutput, cellTextOutput{end+1}] = evaluator.evaluate(fcn, nOut, args);
Error in dctEvaluateTask>iEvaluateTask (line 141)
nEvaluateTask();
Error in dctEvaluateTask (line 57)
[resultsFcn, taskPostFcn, taskEvaluatedOK] = iEvaluateTask(job, task, runprop);
Error in distcomp_evaluate_filetask_core>iDoTask (line 149)
dctEvaluateTask(postFcns, finishFcn);
Error in distcomp_evaluate_filetask_core (line 48)
iDoTask(handlers, postFcns);
Error using parallel.Job/fetchOutputs (line 869)
An error occurred during execution of Task with ID 1.
Error in SOExample (line 14)
job1Results = fetchOutputs(job1);
Caused by:
Index exceeds matrix dimensions.
The file 'Historical1Step' is the script I am trying to run. The first lines (until the code falls over) are:
wrkDir = 'V:\Individual\SOFNN'; % this is where the files are on cluster headnode
wrkFldr = [wrkDir '\ExcelSheets\1-stepAhead\']; % location of excel sheets
%%
folder = dir(wrkFldr);
isub = [folder(:).isdir]; % data is stored in sub-directory based on stock symbol
stockNames = {folder(isub).name}'; % extract stock names from names of sub-dirs
stockNames(ismember(stockNames,{'.','..'})) = []; % remove names '.' and '..'
for i = 1:1 % this loop should read in data for stock i from correct sub-dir
close all;
clc;
sym = stockNames{i};
disp(['Analysing data for stock ' sym]);
fldrName = strcat(wrkFldr,'\', sym, '\');
end % added for completion
In your code, you're using a mapped-drive letter on the workers. Typically, workers cannot see mapped-drive letters because of the way the processes are launched. Try using a UNC path instead. A little more info in the documentaton here : http://www.mathworks.com/help/distcomp/troubleshooting-and-debugging.html

Indexing matrices in matlab

So I have a script that I run j times. The following line produces an error:
[evec(:,:,j), eval(:,:,j)] = eig(T(:,:,j));
Error using mupadmex
Error in MuPAD command: Cannot compute the explicit
representation of the eigenvalues; use
'numeric::eigenvectors'. [linalg::eigenvectors]
Error in sym/mupadmexnout (line 2080)
out = mupadmex(fcn,args{:});
Error in sym/eig (line 68)
[V,D,p] = mupadmexnout('symobj::eigenvectors',A);
Error in SingleLayer (line 86)
[evec(:,:,j), eval(:,:,j)] = eig(T(:,:,j));
That is the error message I get. Am I correct creating 3 "sheets" (not sure how to describe it) like this. I

MATLAB error while convert str2num

i'm completely new to matlab and this is my first question.
I found a program like this
x = inputdlg('foo');
x = str2num(x{1})
and trying to make some gui from it, put this line to callback function of push button:
x=get(handles.edit1, 'String')
x=str2num(x{1})
and it works, but not after i add this the same thing with different variable
y=get(handles.edit2, 'String')
y=str2num(y{1})
command window said
Cell contents reference from a non-cell array object.
Error in regresilinear>pushbutton1_Callback (line 128)
x=str2num(x{1})
Error in gui_mainfcn (line 96)
feval(varargin{:});
Error in regresilinear (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in
#(hObject,eventdata)regresilinear('pushbutton1_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating uicontrol Callback
I found out that the output from command window is different when it's running and not with the same input.
When it got errors:
x =
0 1 2 3
when not (the first time)
x =
'0 1 2 3'
It doesn't give any error if i delete the str2num line.
I hope somebody can help fix the problem.
Start with a clear workspace and
x=get(handles.edit1, 'String');
x=str2num(x);
or better:
x=str2num(get(handles.edit1, 'String'));
{} are used for accessing the elements of a cell array. You are probably trying to use it on a string and that is why you are getting that error.