Matlab postset method sample fails - matlab

I'm trying to call a function right after I change some properties of an object in Matlab. I went to the documentation and found this sample code:
classdef PropListener < handle
properties (SetObservable, AbortSet)
PropOne
PropTwo
end
methods
function obj = PropListener(evtobj)
if nargin > 0
addlistener(evtobj,'PropOne','PostSet',#PropListener.handlePropEvents);
addlistener(evtobj,'PropTwo','PostSet',#PropListener.handlePropEvents);
end
end
end
methods (Static)
function handlePropEvents(src,evnt)
switch src.Name
case 'PropOne'
display('I was here!');
case 'PropTwo'
display('I was here too!');
end
end
end
end
I saved this into a file, went to the console and tryed
test1=PropListener
test1.PropOne=1
and it doesn't show the "I was here!" message. The rest works perfectly.
After some debuging, I found 2 problems:
1 - It calls the constructor method without arguments, therefore
if(argin>0)
returns always false and it never creates the listeners.
2 - If I remove the if/end structure, when I call the constructor
test1 = PropListener
Matlab returns "Error using PropListener (line 9)
Not enough input arguments."
(line 9 is the line with the following statement)
addlistener(evtobj,'PropOne','PostSet',#PropListener.handlePropEvents);
Now, if I remove the whole constructor method and call
addlistener(evtobj,'PropOne','PostSet',#PropListener.handlePropEvents);
on the command line, everything works, but I would have to remember to call that line while writing my scripts, and I don't want to run that risk.
I'd like to know how could I implement this postset feature, and any help would be greatly appreciated.
Thanks in advance,

Related

Is there a solution to matlab claiming insufficient input arguments when enough are being supplied?

I have a custom function I have made, which requires two input arguments. This is the opening line of the function, clearly showing it needs just two input arugments:
function [file,frame,vertices,edges,faces,faceOrders,edgeOrders] = FOLD_reader(filename,rundocfolder)
The FOLD_reader function is called within another function (FEAfromFOLDVaryingStiffness), using the following line of code:
[~,frame,vertices,~,faces,~,~] = FOLD_reader(filename,rundocfolder);
To which matlab claims:
Not enough input arguments.
Error in FEAfromFOLDVaryingStiffness (line 12)
[~,frame,vertices,~,faces,~,~] = FOLD_reader(filename,rundocfolder);"
However, if I copy and paste the offending line into the command window, it works perfectly. The filename and rundocfolder variables are definitely defined in FEAFromFoldVaryingStiffness which calls FOLD_reader, as they are among the input arguments of the FEAFromFold(etc) function itself.
Has anyone had any experience with this seemingly bizzarre error? To me it makes no sense at all.
If it's a help here are the lines up to the error point inside FEAfromFOLDVaryingStiffness:
function [] = FEAfromFOLDVaryingStiffness(filename,meshsize,displacement,m,n,stiffnessvary,rundocfolder)
%Comments ommitted for brevity
[~,frame,vertices,~,faces,~,~] = FOLD_reader(filename,rundocfolder);
I'm an idiot, I called the FEAfromFOLDVaryingStiffness with one too few arguments, I'd left out m or n or something and so the last input variable (rundocfolder) was undefined, which showed up as an error with fold_reader inside the FEAfromFOLDVaryingStiffness function, instead of where the error actually was: the top level script.

Matlab 'main' function isn't reading local functions

I have a code in matlab (~1000 lines) that constists of about 15 functions. The code runs fine with each function as a different script, but I want to put them all into one file so I can use the publish function more easily. However, when I put them all together my 'main' function isn't recognizing the local functions. Here's what it looks like:
function full_function()
...
values = fvalues(0);
...
end
function values = fvalues(state)
...
end
When I try to run it, it gives me
"Undefined function 'fvalues' for input arguments
of type 'double'.
Error in full_function (line 32)
values = fvalues(0);"
I've looked all over for how to do local functions and I have no idea what I'm doing wrong. If I right-click on fvalues and hit 'open' it even brings me to the correct portion of the code, so I have no idea why full_function cannot read it. Please help! Thanks.

Matlab assignment - return only odd elements

I wrote code similar to that posted by FeliceM, but when I tried to include the recommended changes/additions I got the following error:
Warning: File: odd_index.m Line: 5 Column: 18
Function with duplicate name "odd_index" cannot be called.
Here's my code:
function odd_index
M=[1:5; 6:10; 11:15; 16:20; 21:25];
M=M(1:2:end, 1:2:end);
end
function M_out = odd_index(M)
M_out = M(1:2:end, 1:2:end);
end
Not quite sure what I'm doing wrong.
It appears to be simply a problem of naming your two functions the same name. Rename the second function (and make sure it's in a separate file with the same name as itself). Really, the first one isn't a function at all, but appears to be a script.
You may want to refer to the MATLAB Getting Started help documentation for more information on functions and scripts. http://www.mathworks.com/help/matlab/getting-started-with-matlab.html

Programmatically save changes of an editable uitable

I created an UItable in Matlab which I fill with various values and options.
It looks like:
the corresponding code is the following:
selector_1 = { 'A'; 'B' ; 'C' };
selector_2 = { 'A.1'; 'A.2'; 'A.3'; ...
'B.1'; 'B.2'; 'B.3'; ...
'C.1'; 'C.2'; 'C.3' };
rows = 5;
f = figure('name','Configuration of output','Position',[200 200 430 25+rows*20],'numbertitle','off','MenuBar','none');
dat = {'select outputfile...', 'select identifier...', 'Specifier', 'Index'};
dat = repmat(dat,rows,1);
columnname = {'Output file ',...
'Identifier ',...
'Specifier ', 'Index'};
columnformat = { {selector_1{:}}, {selector_2{:}}, 'char', 'numeric' };
columneditable = [true true true true];
t = uitable('Units','normalized','Position',...
[0 0 1 1], 'Data', dat,...
'ColumnName', columnname,...
'ColumnFormat', columnformat,...
'ColumnEditable', columneditable,...
'RowName',[]);
set(t, 'Data', dat,'celleditcallback','get(t,''Data'')');
So I run the code and the figure is open. The underlying script has therefore finished.
When I now edit the table my uitable object is changed and after I finished I can get my final configuration with:
finalconfig = get(t,'Data');
But the thing is I need manually type this line, because my script has already finished. If I put this line at the end of my script, I get an error.
So I thought about using the following loop, to detect when I close the table and to store the last configuration
while ~isempty(findobj('name','Configuration of output'))
% some action
end
finalconfig = get(t,'Data');
And I tried everything to put inside the loop, the whole script, just the set command including the celleditcallback, and other things, but nothing worked. Either my script get stucked inside the loop or the display of my table is not updated when I edit a value. I also tried drawnow at different positions. How one handles this situation? How can I automatically store my final results?
I assume "closing the window" is the best action to detect, as I don't think I could implement a "save" button. I also tried to create a gui using GUIDE but got completely lost, I hope to solve it without.
Edit:
I was now able to implement a "save"-button and tried the callback as follows:
uimenu('Label','Save configuration','Callback',#saveConfig);
function saveConfig(~,~)
output = get(t,'Data',);
save([pwd 'output.mat'],'output');
end
also I implemented a custom CloseRequestFcn as suggested by Lucius Domitius Ahenobarbus. But then I have either one of the following problems:
1)
I define everything as a script, everything works fine, but I need to define functions like #saveConfig (actually my favorite) or #my_Closefcn as a unique function-file in my workspace and I have a hard time to pass the right parameters as dat always remains the same, even though it actually gets changend.
(The example from the mathworks site works! But it doesn't need additional parameters.)
2) When I use
function configuration
% my script from above
end
I can implement #saveConfig or #my_Closefcn directly (nested) and I guess the passing of the parameters would work fine. But the editing of my table does not work anymore, throwing the following error:
Error using handle.handle/get
Invalid or deleted object.
Error while evaluating uitable CellEditCallback
How to solve that?
Now that I know that I can even add buttons to an uitable I REALLY like to avoid GUIDE.
My code above is executable, so I'd be glad if you try it to see what my actual problem is, as it is hard to describe.
depending on using GUIDE or not:
use the CloseRequestFcn->
without GUIDE use:
%write your own CloseRequestFcn and set the figure CloseRequest-Callback to it:
set(gcf,'CloseRequestFcn',#my_closefcn)
%use gcf or the handle of the figure directly
and define my_closefcn including a delete statement for the figure-handle, else the figure will not close :)
See the docs for more information about "Redefining the CloseRequestFcn".
with GUIDE:
you can edit the CloseRequestFcn by inspecting the figure. There is a field called CloseRequestFcn that will create the function automatically and you dont need to take care about getting the handle. It will look like this:
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: delete(hObject) closes the figure
delete(hObject);
Now BEFORE deleting the figure, you should be able to get the data of the uitable (if you have the handle) and I would suggest to just assign the data to the base workspace, like:
assignin('base', 'finalTableData', get(myTableHandle,'Data'));
EDIT
as I was not clear enough, see this example:
(use within one single script)->
function test
h=figure;
x=1:10;
mytable=uitable(h,'Data',x);
set(h,'CloseRequestFcn',#myCloseFcn)
%give a unique Tag:
set(h,'Tag', 'myTag')
set(mytable,'Tag','myTableTag')
end
function myCloseFcn(~,~)
myfigure=findobj('Tag','myTag');
myData=get(findobj(myfigure,'Tag','myTableTag'),'Data')
assignin('base','myTestData',myData)
delete(myfigure)
end
in fact, there is no need to take care for the parameters of your Closereq-Callback, if you know how to find the handle of the figure! Just give something to your figure/uitable that you are able to identify it later on. I used 'Tag', because the first thing I would think of, but there would be other parameters as well.
There are only two differences I can think of between running the code directly after the code, or inside the code.
1. Scope
Perhaps you are actually working with functions, rather than scripts. In this case the problem may be that inside your function, something you need is out of scope.
2. Timing
Though it is rare, sometimes the computer may seem to be finished, whilst it is actually still busy (for a few milliseconds or so).
Here are the steps to a general approach:
Make sure there is a trivial line at the place where you want to insert your command (1==1 for example)
Put a breakpoint at the line
Once matlab stops at the breakpoint, wait a second and try to run your command.
If it works I would bet on problem number 2. try placing a pause(1) before your command and see whether it helps.
If it doesn't work you are likely meeting problem number 1. Now it becomes a matter of finding the right place to put your command. And if the command cannot be put somewhere else in the code, perhaps try an ugly evalin(,'base'). However, the latter should really be considered a workaround rather than a solution.

passing array to gui in matlab

I want to pass an array to a gui and display each element of that array on axes...the elements are the filenames of images...I have written a piece of code...this is my xyz.m file from which i want to pass an array "result" to a gui result_image.m
result_image(result);
In opening_fn of the gui i wrote...
result = varargin{1};
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
%axes(handles.axes1);
%imshow(im2fn);
for jj = 1:length(result)
axes(handles.axesjj);
imshow(result(jj));
I am getting an error as str2func
Invalid function name ''
I dunno what is '' here and also iam getting the error on line result_image(result);
Please Help me!
If you have a look at this it will tell you in detail how to add input arguments to your UI. In fact it's a little more complicated than simply adding a varargin to your OpeningFcn arguments. The reason is that you have to edit the bit of code that begins with the words DO NOT EDIT :-)
You must add some bit of code that allows it to determine that it shouldn't run the code gui_State.gui_Callback = str2func(varargin{1});. Normally, this bit of code allows external access to the functions (i.e. UI calbacks) in your file, but because it's inside the if statement if nargin && ischar(varargin{1}), when you pass an argument to your UI that is a string, it thinks you're trying to get a handle to one of the functions in the file and calls str2func on the empty string you passed it (which is in varargin{1}).
So that's why it doesn't work. You could probably fix this simply by using varargin{2} as your input argument instead and opening your UI with result_image([], result), so that ischar(varargin{1}) is false. To make it a bit more robust, you should probably change
if nargin && ischar(varargin{1})
to
if nargin > 0 && nargin < 2 && ischar(varargin{1})
Note that the fact that you have passed it an empty string in the first place is probably indicative of a bug in your code that opens the UI (i.e., whatever generates result).