Java progressbar for matlab, how do you feed the values to it? - swing

I came across an interesting alternative to matlab waitbar which is from java, it follows as below.
jBarHandle = javax.swing.JProgressBar(0, 103);
jBarHandle.setStringPainted(true);
jBarHandle.setIndeterminate(false);
posPanel = getpixelposition(handles.slider1,true);
javacomponent(jBarHandle,posPanel,handles.fig);
jBarHandle.setValue(fix(0));
calling the above code under output function of GUIDE will update the slider with the java enabled one. But how to pass the variable_data into setValue ?
anyone tried this? or have any idea? please help.

You can pass the variable directly to the setValue method of your JProgressBar object. Here I have used javaMethodEDT to ensure that the method is called from the Event Dispatch Thread (EDT). You could also just call jBarHandle.setValue(k) directly.
jBarHandle = javax.swing.JProgressBar(0, 103);
jBarHandle.setStringPainted(true);
jBarHandle.setIndeterminate(false);
fig = figure('Position', [0 0 200 20]);
[jhandle, hhandle] = javacomponent(jBarHandle, [0 0 1 1], fig);
set(hhandle, 'parent', fig, 'Units', 'norm', 'Position', [0 0 1 1])
for k = 1:103
javaMethodEDT('setValue', jBarHandle, k);
pause(0.1);
end
The value that you pass to the progress bar should just be a variable within your local scope. I'm not completely sure why you're overlaying a slider with this progress bar, but you could link the value of these two by simply doing the following
listener = addlistener(handles.slider1, 'Value', 'PostSet', #(s,e)jBarHandle.setValue(e.NewValue));
Then whenever the slider value changes (either programmatically or through the GUI), the progress bar gets updated as well.
More info in the EDT here provided by Yair Altman.
If you want to save your java handle within your GUI you can use the following
setappdata(handles.fig, 'ProgressBar', jBarHandle);
Then from the external function you can retrieve it the following way
figure_handle = findall(0, 'type', 'figure', 'tag', 'fig');
jBarHandle = getappdata(figure_handle, 'ProgressBar');
javaMethodEDT('setValue', jBarHandle, value)

Related

Extracting color from complex function: " Cannot modify global variable 'cColor' in function."

I'd like to extract the "col" color value from this function to be used to paint plots or candle colors. But everything I try creates one error or another. I checked the Script Reference. Shouldn't there be some way to "return" a value, as is usually the case with most functions?
lset(l,x1,y1,x2,y2,col)=>
line.set_xy1(l,x1,y1)
line.set_xy2(l,x2,y2)
line.set_width(l,5)
line.set_style(l, line.style_solid)
line.set_color(l,y2 > y1 ? #ff1100 : #39ff14) //red : green
temp = line.get_price(l,bar_index) // another value to extract
The documentation is showing it like this:
line.new(x1, y1, x2, y2, xloc, extend, color, style, width) → series line
So in your code it's looking differently and also the "new" is missing.
Scrolling a bit up on the linked page shows that there exist indeed methods to retrieve some properties of the line object:
Lines are managed using built-in functions in the line namespace. They include:
line.new() to create them.
line.set_*() functions to modify the properties of an line.
line.get_*() functions to read the properties of an existing line.
line.copy() to clone them.
line.delete() to delete them.
The line.all array which always contains the IDs of all
the visible lines on the chart. The array’s size will depend on
the maximum line count for your script and how many of those you
have drawn. aray.size(line.all) will return the array’s size.
The most simple usage is to instantiate a line object with the correct values directly, like shown here:
//#version=5
indicator("Price path projection", "PPP", true, max_lines_count = 100)
qtyOfLinesInput = input.int(10, minval = 1)
y2Increment = (close - open) / qtyOfLinesInput
// Starting point of the fan in y.
lineY1 = math.avg(close[1], open[1])
// Loop creating the fan of lines on each bar.
for i = 0 to qtyOfLinesInput
// End point in y if line stopped at current bar.
lineY2 = open + (y2Increment * i)
// Extrapolate necessary y position to the next bar because we extend lines one bar in the future.
lineY2 := lineY2 + (lineY2 - lineY1)
lineColor = lineY2 > lineY1 ? color.lime : color.fuchsia
line.new(bar_index - 1, lineY1, bar_index + 1, lineY2, color = lineColor)
Getting the line color from outside is difficult or impossible though as there never exists a method to retrieve it while for other properties those methods exist.
So the most simple way is to create the same funcionality, to get the color that exists inside the line-object, outside too, or only outside.
currentLineColor = y2 > y1 ? #ff1100 : #39ff14
You could try to extend the line-object somehow like this:
line.prototype.get_color = function() {
return this.color;
};
console.log(line.get_color())
I'm not sure if the approach with the prototype is working but it's worth it to try if you need it.

Scilab - calling another GUI within a GUI. Functions not working

I'm quite new to scilab, I have created two GUIs (see example below), with script 2 being called from script 1. However the function in script 2 don't seem to work. Can anyone help?
Script 1
'//////////
f=figure('figure_position',[0,0],'figure_size',[1250,650]);
//////////
delmenu(f.figure_id,gettext('File'))
delmenu(f.figure_id,gettext('?'))
delmenu(f.figure_id,gettext('Tools'))
toolbar(f.figure_id,'off')
handles.dummy = 0 ;
handles.exam=uicontrol(f,'unit','normalized','BackgroundColor', [0.5,1,1],'Enable','on','FontAngle','normal','FontName','helvetica','FontSize',[14],'FontUnits','points','FontWeight','bold','ForegroundColor',[0,0.5,0],'HorizontalAlignment','center','ListboxTop',[],'Max',[1],'Min',[0],'Position',[0.5,0.5,0.1,0.05],'Relief','flat','SliderStep',[0.01,0.1],'String','exam','Style','pushbutton','Value',[0],'VerticalAlignment','middle','Visible','on','Tag','obj102','Callback','exam_callback(handles)')
function exam_callback(handles)
close(f);
clear
exec('costs0-1.sce',-1) ;
endfunction`
Script 2
////////// Defining the figure (size, name etc)/////////////////////////////
f=figure('figure_position',[0,0],'figure_size',[1250,650],'auto_resize','on','background',[8]);
//////////
delmenu(f.figure_id,gettext('File'))
delmenu(f.figure_id,gettext('?'))
delmenu(f.figure_id,gettext('Tools'))
toolbar(f.figure_id,'off')
//Cabinet - TEXT
handles.obj17=uicontrol(f,'unit','normalized','BackgroundColor',[1,1,1],'Enable','on','FontAngle','normal','FontName','helvetica','FontSize',[12],'FontUnits','points','FontWeight','normal','ForegroundColor',[0,0,0],'HorizontalAlignment','center','ListboxTop',[],'Max',[1],'Min',[0],'Position',[0.15,0.93,0.1,0.05],'Relief','flat','SliderStep',[0.01,0.1],'String','Cabinet','Style','text','Value',[0],'VerticalAlignment','middle','Visible','on','Tag','obj17','Callback','')
// Cabinet - POP UP MENU
handles.service=uicontrol(f,'unit','normalized','BackgroundColor',[0.8,0.8,0.8],'Enable','on','FontAngle','normal','FontName','helvetica','FontSize',[12],'FontUnits','points','FontWeight','normal','ForegroundColor',[0,0.5,0],'HorizontalAlignment','center','ListboxTop',[],'Max',[1],'Min',[0],'Position',[0.25,0.93,0.15,0.05],'Relief','flat','SliderStep',[0.01,0.1],'String','1|2','Style','popupmenu','Value',[1],'VerticalAlignment','middle','Visible','on','Tag','service','Callback','service_callback(handles)')
// CALCULATE PUSHBUTTON
handles.Calculate=uicontrol(f,'unit','normalized','BackgroundColor',[0,0.8,0],'Enable','on','FontAngle','normal','FontName','helvetica','FontSize',[16],'FontUnits','points','FontWeight','bold','ForegroundColor',[0,0,0],'HorizontalAlignment','center','ListboxTop',[],'Max',[1],'Min',[0],'Position',[0.22,0.02,0.15,0.08],'Relief','raised','SliderStep',[0.01,0.1],'String','CALCULATE','Style','pushbutton','Value',[0],'VerticalAlignment','middle','Visible','on','Tag','Calculate','Callback','Calculate_callback(handles)')
// Resources- TEXT
handles.Resourcestxt=uicontrol(f,'unit','normalized','BackgroundColor',[1,1,1],'Enable','on','FontAngle','normal','FontName','helvetica','FontSize',[14],'FontUnits','points','FontWeight','bold','ForegroundColor',[0,0.5,0],'HorizontalAlignment','center','ListboxTop',[],'Max',[1],'Min',[0],'Position',[0.75,0.95,0.20,0.05],'SliderStep',[0.01,0.1],'String','Resources in hours','Style','text','Value',[0],'VerticalAlignment','middle','Visible','on','Tag','','Callback','')
// TOTAL hours - TEXT
handles.totalhourstxt=uicontrol(f,'unit','normalized','BackgroundColor',[1,1,1],'Enable','on','FontAngle','normal','FontName','helvetica','FontSize',[14],'FontUnits','points','FontWeight','bold','ForegroundColor',[0,0.5,0],'HorizontalAlignment','center','ListboxTop',[],'Max',[1],'Min',[0],'Position',[0.75,0.75,0.12,0.05],'SliderStep',[0.01,0.1],'String','Total Hours','Style','text','Value',[0],'VerticalAlignment','middle','Visible','on','Tag','','Callback','')
// hardware hours - text
handles.totalhours=uicontrol(f,'unit','normalized','BackgroundColor',[0.95,1,1],'Enable','on','FontAngle','normal','FontName','helvetica','FontSize',[14],'FontUnits','points','FontWeight','bold','ForegroundColor',[0,0.5,0],'HorizontalAlignment','center','ListboxTop',[],'Max',[1],'Min',[0],'Position',[0.88,0.75,0.08,0.05],'SliderStep',[0.01,0.1],'String','','Style','text','Value',[0],'VerticalAlignment','middle','Visible','on','Tag','totalhours','Callback','')
function Calculate_callback(handles)
if handles.service.value == 1 then
resource_hrs = 2
end
if handles.service.value == 2 then
resource_hrs = 10
end
set(handles.totalhours,'String',string(resource_hrs));
endfunction
Problem
It is a scoping problem. When function exam_callback() gets called it runs the other script with exec('costs0-1.sce',-1).
In that script you define the function Calculate_callback(handles). This goes out of scope and is deleted when exam_callback() is finished and as such can't be called when the button is pressed.
The second problem is that the handles are not globally affected, so when leaving exam_callback() the handles of the second Cost Gui are not added to handles.
Solution
You can move the generating of the GUI into a function createCostGui() and then load script2 at the start of script1 with exec('costs0-1.sce',-1);.
To make Calculate_callback(handles) function discard the handles argument and use the tags to find the handles
function Calculate_callback()
serviceHandle = findobj('tag','service');
if serviceHandle.value == 1 then
resource_hrs = 2
end
if serviceHandle.value == 2 then
resource_hrs = 10
end
totalHoursHandle = findobj('tag','totalhours');
set(totalHoursHandle,'String',string(resource_hrs));
endfunction
Further remarks
Text elements are generally static and thus don't need a Callback argument.
If you want an argument to stay at its default value, you don't need to specify them.
From the Scilab documentation:
h = uicontrol(PropertyName, PropertyValue,...) creates an uicontrol and assigns the specified properties and values to it. It assigns the default values to any properties you do not specify. The default uicontrol style is a "Pushbutton". The default parent is the current figure. See the Properties section for information about these and other properties.
Small remark on your question
Next time an error message could help with making your question more specific.

How do I set a function to a variable in MATLAB

As a homework assignment, I'm writing a code that uses the bisection method to calculate the root of a function with one variable within a range. I created a user function that does the calculations, but one of the inputs of the function is supposed to be "fun" which is supposed to be set equal to the function.
Here is my code, before I go on:
function [ Ts ] = BisectionRoot( fun,a,b,TolMax )
%This function finds the value of Ts by finding the root of a given function within a given range to a given
%tolerance, using the Bisection Method.
Fa = fun(a);
Fb = fun(b);
if Fa * Fb > 0
disp('Error: The function has no roots in between the given bounds')
else
xNS = (a + b)/2;
toli = abs((b-a)/2);
FxNS = fun(xns);
if FxNS == 0
Ts = xNS;
break
end
if toli , TolMax
Ts = xNS;
break
end
if fun(a) * FxNS < 0
b = xNS;
else
a = xNS;
end
end
Ts
end
The input arguments are defined by our teacher, so I can't mess with them. We're supposed to set those variables in the command window before running the function. That way, we can use the program later on for other things. (Even though I think fzero() can be used to do this)
My problem is that I'm not sure how to set fun to something, and then use that in a way that I can do fun(a) or fun(b). In our book they do something they call defining f(x) as an anonymous function. They do this for an example problem:
F = # (x) 8-4.5*(x-sin(x))
But when I try doing that, I get the error, Error: Unexpected MATLAB operator.
If you guys want to try running the program to test your solutions before posting (hopefully my program works!) you can use these variables from an example in the book:
fun = 8 - 4.5*(x - sin(x))
a = 2
b = 3
TolMax = .001
The answer the get in the book for using those is 2.430664.
I'm sure the answer to this is incredibly easy and straightforward, but for some reason, I can't find a way to do it! Thank you for your help.
To get you going, it looks like your example is missing some syntax. Instead of either of these (from your question):
fun = 8 - 4.5*(x - sin(x)) % Missing function handle declaration symbol "#"
F = # (x) 8-4.5*(x-sin9(x)) %Unless you have defined it, there is no function "sin9"
Use
fun = #(x) 8 - 4.5*(x - sin(x))
Then you would call your function like this:
fun = #(x) 8 - 4.5*(x - sin(x));
a = 2;
b = 3;
TolMax = .001;
root = BisectionRoot( fun,a,b,TolMax );
To debug (which you will need to do), use the debugger.
The command dbstop if error stops execution and opens the file at the point of the problem, letting you examine the variable values and function stack.
Clicking on the "-" marks in the editor creates a break point, forcing the function to pause execution at that point, again so that you can examine the contents. Note that you can step through the code line by line using the debug buttons at the top of the editor.
dbquit quits debug mode
dbclear all clears all break points

Cannot pass function handle as an argument of a function

I'm new to Matlab and I'm trying to write custom function in matlab that would take function handle as one of its arguments.
I'm getting this error all the time:
Error using subsindex
Function 'subsindex' is not defined for values of class 'function_handle'.
Trying to debug I performed following test: I run command x = fminbnd(#humps, 0.3, 1). I proceeded as expected - I got result x = 0.6370.
So I created custom function called train and I copied ALL the code of function fminbnd to the file train.m. The only thing that I changed is the name, so that code of functions fminbnd and train is now identical except for the names.
Now I run both functions with the same argument and the custom function throws error while original fminbnd returns correct answer.
Here is the code:
>> x = fminbnd(#humps, 0.3, 1)
x =
0.6370
>> x = train(#humps, 0.3, 1)
Error using subsindex
Function 'subsindex' is not defined for values of class 'function_handle'.
Here is header of function train (everything else is copied from fminbnd):
function [xf,fval,exitflag,output] = train(funfcn,ax,bx,options,varargin)
Where is the problem?
Doing a which train showed me that there is a function in the neural network toolbox of the same name.
/Applications/MATLAB_R2009b.app/toolbox/nnet/nnet/#network/train.m % network method
You may be running the nnet train.m rather than the one you think you're running. Are you in the directory containing your train.m? When I made sure I was in the right directory, I got it to work:
>> which train
/Users/myuserid/train.m
>> x = train(#humps,0.3,1)
x =
0.6370
Maybe you can name your file something else like myfminbnd.m instead?
Instead of duplicating the whole fminbnd function, try:
function varargout = myfminbnd(varargin)
varargout = cell(1,nargout(#fminbnd));
[varargout{:}] = fminbnd(varargin{:});
end
this will work as an "alias" to the existing function:
>> fminbnd(#(x)x.^3-2*x-5, 0, 2)
ans =
0.8165
>> myfminbnd(#(x)x.^3-2*x-5, 0, 2)
ans =
0.8165
(you can get the other output arguments as well)

How can I use function callback ('StopFcn' , 'TimerFcn' )for audiorecorder object in MATLAB?

I want to execute the function 'get_pitch(samples,fs,winsize,winshift)' while during recording through audiorecorder object. To do that, I found that 'function callback' would be helpful to do that.
So I try to this code.
% assume fs,winsize,winshift is given.
T = 0.1; % in seconds
samples = cell{100,1};
r = audiorecorder(fs,16,1);
k=1;
r.TimerPeriod = 0.1;
r.StopFcn = 'samples{k} = getaudiodata(r);';
r.TimerFcn = {#get_pitch,samples{k},winsize,winshift};
while 1
record(r,T);
k=k+1;
end
But following exception occurs during execution.
1) after record(r,T) is executed. (StopFcn is now called)
??? Error using ==> eval
Undefined function or variable 'r'.
2) after StopFcn is called (TimerFcn is now called)
In this phase, get_pitch function have totally wrong parameters. For example, parameter
in the position samples{k} change to 'audiorecorder object'.
It seems that I do not know exact use of 'StopFcn' & 'TimerFcn'.
Is there anyone who can give me some advice? I really appreciate all of your comments.