Define custom linestyles in Octave for use on multiple figures - octave

I'd like to define line styles in Octave (like in gnuplot) for further usage:
I was thinking about something like that:
styles = {['color',[.5 .2 .8],'--', 'linewidth', 1.25], ['or', markersize, 4],
['-sb', markersize, 2]}
plot (x,y, styles{1})
plot (x,y, styles{2})
and so on. But such a thing didn't work. Does someone have any suggestions how to solve this?
Thanks in advance.

Let's have a look, what MATLAB does and copy the ideas: You can use Comma-Separated Lists as Function Call Arguments. Actually, there's an example describing exactly, what you want to achieve. Nevertheless, to get this working as you'd like to, you also have to "disassemble" the LineSpec properly. Please see the following code snippet to get the solution for the examples given by you.
x = linspace(0, 2*pi, 50);
% styles = {['color',[.5 .2 .8],'--', 'linewidth', 1.25], ['or', markersize, 4], ['-sb', markersize, 2]}
styles = {
{'Color', [.5 .2 .8], 'LineStyle', '--', 'LineWidth', 1.25}, ...
{'Color', 'r', 'Marker', 'o', 'MarkerSize', 4}, ...
{'Color', 'b', 'LineStyle', '-', 'Marker', 's', 'MarkerSize', 2} ...
};
figure(1);
hold on;
for ii = 1:numel(styles)
plot(x, sin(x + ii * pi/4), styles{ii}{:});
end
hold off;
legend();
And, here is an exemplary output:

Related

How to graph the function in matlab?

I have the following 2n*π-periodic function F(x) = sin(x/n) and I need to graph the dx/dt = γ - F(x) on the segment from 0 to 2pi. So it should look like this. I tried to do it matlab this way:
gamma = 1.01;
n=3;
[t,phi] = ode45(#(t,x)gamma-sin(x/n), [0,400], pi);
[t1,phi1] = ode45(#(t,x)gamma-sin(x/n), [112,400], 0);
[t2,phi2] = ode45(#(t,x)gamma-sin(x/n), [231,250], 0);
figure();
plot(t, phi, 'k', t1, phi1, 'k', t2, phi2, 'k');
ylim([0 2*pi]);
yticks([0 pi 2*pi]);
yticklabels(["0" "\pi" "2\pi"]);
grid on; grid minor;
title('\itsin(x/n)')
but I only got something like this. So there the lines are not transferred, but "begin anew". does anyone here know how to do that?
I get a plot similar to your first sketch, and based on your code in the comments (in future, put such additions into the question itself, use formatting to mark it as addition, and cite it then in the comment) with the changes
use pi as initial point as seen in the drawing,
use the options of the ODE solver to restrict the step size, directly and by imposing error tolerances
your original time span covers about 3 periods, reduce this to [0, 200] to get the same features as the drawing.
gamma = 1.01; n=3;
opts = odeset('AbsTol',1e-6,'RelTol',1e-9,'MaxStep',0.1);
[t, phi] = ode45(#(t,x)gamma-sin(x/n), [0,200], pi, opts);
phi = mod(phi, 2*pi);
plot(t, phi, 'k');
ylim([0 2*pi]); yticks([0 pi 2*pi]); yticklabels(["0" "\pi" "2\pi"]);
grid on; grid minor;
title('\itsin(x/n)')
To get more elaborate, use events to get points on the numerical solution where it exactly crosses the 2*pi periods, then use that to segment the solution plot (styling left out)
function [ res, term, dir ] = event(t,y)
y = mod(y+pi,2*pi)-pi;
res = [ y ];
dir = [1]; % only crossing upwards
term = [0]; % do not terminate
end%function
opts = odeset(opts,'Events',#(t,y)event(t,y));
sol = ode45(#(t,x)gamma-sin(x/n), [0,200], pi, opts);
tfs = [ sol.xe; sol.x(end) ]
N = length(tfs)
clf;
t0 = 0;
for i=1:N
tf = tfs(i);
t = linspace(t0+1e-2,tf-1e-2,150);
y = deval(sol,t); % octave: deval=#(res,t) interp1(res.x, res.y,t)
y = mod(y,2*pi);
plot(t, y);
hold on;
t0=tf;
end;
hold off;

Why am I getting out of range error?

I'm building a function to extract all negatives from the list xs. Then I'm appending those negatives to a list negatives, and adding list negatives to list new_home, which may or may not already have values to it. The function was working before I added xs.pop(num). Why is it now out of range?
Here is the code:
def extract_negatives(xs,new_home=None):
negatives=[]
if new_home==None:
for num in range(len(xs)):
if xs[num] <0:
negatives.append(xs[num])
xs.pop(num)
return negatives
else:
for num in range(len(xs)):
if xs[num] <0:
new_home.append(xs[num])
xs.pop(num)
return new_home.append(negatives)
As stated, you are mutating list passed to the function and hence index is getting messed up.
If you must delete from passed list then one idea is to delete at the end of function just before you returned result. That way mutation wont affect indexing.
Also , I don't understand why you have if and else both looking for xs<0 . I cleaned up your function and got it working.
EDIT1 -Working Code
def extract_negatives(xs,new_home):
negatives=[]
for num in range(len(xs)):
if xs[num] <0:
negatives.append(xs[num])
new_home = new_home + negatives
for i in negatives:
xs.remove(i)
return new_home
new_home=[-9,-11,]
xs = [ 2 ,-3, 4, -5, 6, -7]
new_home = extract_negatives(xs,new_home)
print new_home
Output
>>>
[-9, -11, -3, -5, -7]
>>> xs
[2, 4, 6]

Replace Square Brackets with parentheses in Ruby

Using Ruby 1.9.
I have a array [1,2,3]
I need to convert it to a format ('1', '2', '3') in order to apply it inside SQL queries (IN Statements) and the database is MySQL. Please suggest some good solution.
Thanks :)
Looking at the comments above not sure you still want to do this, but just for fun:
"('#{ [1,2,3].map(&:to_s).join("\',\'") }')"
#=> "('1','2','3')"
UPDATE: Based on comments from #tadman
assuming a SQL implementation here is some pseudo code:
irb(main):003:0> array = [1,2,3,4]
=> [1, 2, 3, 4]
irb(main):004:0> array.map{|id| "$#{id}"}.join(",")
=> "$1,$2,$3,$4"
irb(main):011:0> ["SELECT * FROM table WHERE id IN (#{array.map{|id| "$#{id}" }.join(',')})", array]
=> ["SELECT * FROM table WHERE id IN ($1,$2,$3,$4)", [1, 2, 3, 4]]

Problems with GUI, unable to use handles to store variables

I am creating a GUI where a user inputs a value and when he presses a pushbutton it runs an external function and displays error messages. I am having trouble with inserting the variable successfully in the GUI coding. I am confused as to where to insert my variable. I have tried handles but unfortunately its not working.
% --- Executes just before Stallfunction is made visible.
function Stallfunction_OpeningFcn(hObject, ~, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to Stallfunction (see VARARGIN)
% Choose default command line output for Stallfunction
handles.user_entry = user_entry;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes Stallfunction wait for user response (see UIRESUME)
% uiwait(handles.figure1);
I have inserted the variable in the above code, which is 'user_entry' is that correct?
user_entry is not assigned a value in your function. If you launch your GUI by passing a value for user_entry like this:
Stallfunction(user_entry)
then the first lines of your code in the openingFcn should be:
if ~isempty(varargin)
user_entry = varargin{1};
else
error('please start the GUI with an input value')
end
After this, you can assign user_entry to the handles structure as you're doing already.
Try this:
function num = get_num()
fig = figure('Units', 'characters', ...
'Position', [70 20 30 5], ...
'CloseRequestFcn', #close_Callback);
edit_num = uicontrol(...
'Parent', fig, ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [1 1 10 3], ...
'HorizontalAlignment', 'left', ...
'String', 'init', ...
'Callback', #edit_num_Callback);
button_finish = uicontrol( ...
'Parent', fig, ...
'Tag', 'button_finish', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [15 1 10 3], ...
'String', 'Finish', ...
'Callback', #button_finish_Callback);
% Nested functions
function edit_num_Callback(hObject,eventdata)
disp('this is a callback for edit box');
end
function button_finish_Callback(hObject,eventdata)
% Exit
close(fig);
end
function close_Callback(hObject,eventdata)
num_prelim = str2num(get(edit_num,'string'));
if(isempty(num_prelim))
errordlg('Must be a number.','Error','modal');
return;
end
num = num_prelim;
delete(fig);
end
waitfor(fig);
end
See if you can mess with this and get what you want. Also, learn to use nested functions and how callbacks work in matlab. Save this as a function file and then call "num = getnum;"

Catch exception in Mathematica without having to run computations twice

I have to run a number of NMinimize commands on various instances. Some of these runs failed to converge.
I want to identify which ones failed to converge and obtain the current solution that Mathematica found.
Searches on other posts suggested using Check[], but it does not return the result once it comes out of the error.
So currently, I have the inefficient implementation as follows:
allfit1 = ConstantArray[0,16];
For[i = 1, i <= 16, i++, (
allfit1[[i]] = Check[
{0, NMinimize[f[x,data[[i]]], x]},
{1, NMinimize[f[x,data[[i]]], x]}
]
)]
As you see I am having to execute NMinimize twice, which is wasteful and time consuming.
Is there a better way?
As a minor change: you could store the result in a variable:
Block[{res},
Check[{0, res = NMinimize[...]}, {1, res}]
]
You could do
Table[Reap#Quiet#Check[Sow#NMinimize[f[x, d], x]; 1, 0]~
Extract~{{1}, {2, 1, 1}}, {d, data}]