How to print a complex number without percent sign in Scilab? - scilab

I tried this
a = 1+3*%i;
disp("a = "+string(a))
I got a = 1+%i*3 , but what I want is a = 1. + 3.i
So is there any method in Scilab to print a complex number without the percent sign?

Similarly to Matlab, you can format the output string by including the real and imaginary parts separately.
mprintf('%g + %gi\n', real(a) , imag(a))
However, that looks pretty ugly when the imaginary part is negative. I suggest writing a formatting function:
function s = complexstring(a)
if imag(a)>=0 then
s = sprintf('%g+%gi', real(a) , imag(a))
else
s = sprintf('%g%gi', real(a) , imag(a))
end
endfunction
Examples:
disp('a = '+complexstring(1+3*%i))
disp('b = '+complexstring(1-3*%i))
Output:
a = 1+3i
b = 1-3i

Related

Plot title with variable value and subscript characters in Julia

I'm trying to have a plot title which contains variable values and also characters with subscripts, however when I try:
title = "ηₛ = $η̂[Pa S] , μₛ = $μ̂[Pa], μₚ = $μ̂ₚ[Pa] , ηₚ = $η̂ₚ[Pa S] \n α = $α̂ , ζ = $ζ̂"
Inside the plot function, the title appears with X marks where the subscripts are. I tried to use LaTeX ```title = L" .." but then the variable values don't appear.
Is there any way to have both in the title I need?
If you want a fully working solution this is what I think you need to do, note that %$ is used for interpolation:
title = L"\eta_1 = %$(η̂[Pa, S])"
The reason is that, while some of the characters will be rendered correctly as Bill noted, not all of them will unless you use LaTeXStrings.jl.
See:
help?> LaTeXStrings.#L_str
L"..."
Creates a LaTeXString and is equivalent to latexstring(raw"..."), except that %$ can be used for interpolation.
julia> L"x = \sqrt{2}"
L"$x = \sqrt{2}$"
julia> L"x = %$(sqrt(2))"
L"$x = 1.4142135623730951$"

scilab, passing parameters to the function and changing variable type

I'm trying to build a GUI to output plots for control system design when input parameters of transfer function.I got some problems on passing parameters to the function and changing variable type.
I've got a stucture with examples of simulation parameters:
param = [];
param.parameter = "s";
param.dom = "c"; //domain(c for continuous, d for discrete)
param.num = 1; //numerator of transfer function
param.den = "(s+1)^3"; //denominator
param.fmin = 0.01; //min freq of the plot
param.fmax = 100; //max freq
and a function to plot the graphs:
// display function
function displayProblem(param)
parameter = param.parameter;
dom = param.dom;
num = param.num;
den = param.den;
fmin = param.fmin;
fmax = param.fmax;
s = poly(0,parameter.string);
h = syslin(dom.string,num,den);
// Plotting of model data
delete(gca());
//bode(h,fmin1,fmax1);
gain_axes = newaxes();
gain_axes.title.font_size = 3;
gainplot(h,fmin,fmax);
gain_axes.axes_bounds = [1/3,0,1/3,1/2];
gain_axes.title.text = "Gain Plot";
phase_axes = newaxes();
gain_axes.title.font_size = 3;
phaseplot(h,fmin,fmax);
phase_axes.axes_bounds = [1/3,1/2,1/3,1/2];
phase_axes.title.text = "Phase Plot";
phase_axes = newaxes();
gain_axes.title.font_size = 3;
nyquist(h);
phase_axes.axes_bounds = [2/3,0,1/3,1/2];
phase_axes.title.text = "Nyquist Plot";
endfunction
There's something wrong when passing numerator and denominator to the function. The variable type doesn't match what syslin required. If I replace 'num' and 'den' with '1' and '(s+1)^3', everything worked quite well. Also if I try this line-by-line in control panel, it works, but not in SciNotes. What's the proper way to deal with this? Any suggestion will be greatly appreaciated.
There are 3 errors in your code: Replace
param.den = "(s+1)^3"; //denominator
with
param.den = (%s+1)^3;
Indeed, Scilab has a built-in polynomial type. Polynomials are not defined as a string nor as a vector of coefficients. The predefined constant %s is the monomial s.
In addition,
s = poly(0,parameter.string);
is useless (and incorrect: parameter would work, while parameter.string won't since parameter has no string field: It IS the string). Just remove the line.
As well, replace
h = syslin(dom.string,num,den);
with simply
h = syslin(dom, num,den);
Finally, although the figure's layout is not simple, you can use bode() in the function in the following way:
// delete(gca());
subplot(1,3,2)
bode(h, fmin, fmax)
subplot(2,3,3)
nyquist(h)
gcf().children.title.text=["Nyquist Plot" "Phase Plot" "Gain Plot"]
All in one, the code of your function may resume to
function displayProblem(param)
[dom, num, den] = (param.dom, param.num, param.den);
[fmin, fmax] = (param.fmin, param.fmax);
h = syslin(dom, num,den);
// Plotting of model data
subplot(1,3,2)
bode(h,fmin,fmax);
subplot(2,3,3)
nyquist(h);
gcf().children.title.text=["Nyquist Plot" "Phase Plot" "Gain Plot"];
endfunction
Best regards

Large Integer division error in Julia when using UInt128 data type

I get incorrect results when I divide large integers of type UInt128. The error seems to occur about the same spot, significant figure wise, that a float64 will round its result. Using something simple, like dividing by 2, I can easily verify that I am not getting the correct answer. Also I can use BigInt types to verify that I am indeed seeing what seem to be significant figure errors while using UInt128 variable.
I am still fairly new to Julia and not familiar enough with the inner workings of the language to know why this is happening and when to expect these kinds of results. Can someone please give me some insight as to why/how this is occurring.
For example:
xb::BigInt = big"40282366920938463463374607431768211456"
ub::BigInt = big"2"
xu::UInt128 = parse(UInt128,"40282366920938463463374607431768211456")
uu::UInt128 = parse(UInt128, "2")
println("Initial value for xb = " , xb)
println("Initial value for xu = " , xu)
gb::BigInt = xb / ub
gu::UInt128 = xu / uu
g1::UInt128 = UInt128(40282366920938463463374607431768211456) / UInt128(2)
g2 = UInt128(40282366920938463463374607431768211456) / UInt128(2)
println("Division result using BigInt = ", gb)
println("Division result using UInt128 variables = ", gu)
println("Division result using UInt128 typecasts = ", g1)
println("Division result using UInt128 julia decides = ", g2)
println(typeof(g2))
Output:
julia> include("uint128_test.jl")
Initial value for xb = 40282366920938463463374607431768211456
Initial value for xu = 40282366920938463463374607431768211456
Division result using BigInt = 20141183460469231731687303715884105728
Division result using UInt128 variables = 20141183460469232747289327097010454528
Division result using UInt128 typecasts = 20141183460469232747289327097010454528
Division result using UInt128 julia decides = 2.0141183460469233e37
Float64
Integer division in Julia promotes to Float64. you want to use div or ÷ for integer division.
For a very brief version of this, 3/2 = 1.5

Using inttrap and diff to get the length of a curve in Scilab

How can you get the length of the curve down below between 0 and 4*pi? The commands you should use are inttrap and diff. Here is what I have now:
t=linspace(0,4*%pi)
x=(4+sin(a*t)).*cos(3*t)
y=(4+sin(a*t)).*sin(3*t)
z=cos(3*t)
xx=diff(x)
yy=diff(y)
zz=diff(z)
aid=sqrt(xx^2+yy^2+zz^2)
length=inttrap([t],aid)
Getting error message, the last step is not right.
The reason for error message is that t and aid have different sizes. And that is because diff returns a vector with 1 entry fewer than the input. You can see how it works on an example: diff([3 1 5]) is [-2 4].
To fix this, use t(1:$-1), which omits the last entry of t. That is,
len = inttrap(t(1:$-1), aid)
(Please don't use length, which is a function name in Scilab.)
Another problem you have is that diff is just differences, not a derivative. To get the derivative, you need to divide by the step size, which in your case is t(2)-t(1).
Also, the syntax xx^2 is deprecated for elementwise power; use xx.^2 instead
t = linspace(0,4*%pi)
a = 1
x = (4+sin(a*t)).*cos(3*t)
y = (4+sin(a*t)).*sin(3*t)
z = cos(3*t)
step = t(2)-t(1)
xx = diff(x)/step
xy = diff(y)/step
xz = diff(z)/step
aid = sqrt(xx.^2+yy.^2+zz.^2)
len = inttrap(t(1:$-1), aid)

Torch nn. Current error always is nan

I've wrote the following code:
require 'nn'
require 'cunn'
file = torch.DiskFile('train200.data', 'r')
size = file:readInt()
inputSize = file:readInt()
outputSize = file:readInt()
dataset = {}
function dataset:size() return size end;
for i=1,dataset:size() do
local input = torch.Tensor(inputSize)
for j=1,inputSize do
input[j] = file:readFloat()
end
local output = torch.Tensor(outputSize)
for j=1,outputSize do
output[j] = file:readFloat()
end
dataset[i] = {input:cuda(), output:cuda()}
end
net = nn.Sequential()
hiddenSize = inputSize * 2
net:add(nn.Linear(inputSize, hiddenSize))
net:add(nn.Tanh())
net:add(nn.Linear(hiddenSize, hiddenSize))
net:add(nn.Tanh())
net:add(nn.Linear(hiddenSize, outputSize))
criterion = nn.MSECriterion()
net = net:cuda()
criterion = criterion:cuda()
trainer = nn.StochasticGradient(net, criterion)
trainer.learningRate = 0.02
trainer.maxIteration = 100
trainer:train(dataset)
And it must works good (At least I think so), and it works correct when inputSize = 20. But when inputSize = 200 current error always is nan. At first I've thought that file reading part is incorrect. I've recheck it some times but it is working great. Also I found that sometimes too small or too big learning rate may affect on it. I've tried learning rate from 0.00001 up to 0.8, but still the same result. What I'm doing wrong?
Thanks,
Igor

Resources