Hey guyz. Can help me on this?
if size(cost,1) == 2
A = (4*Pdt*cost(1,3)*cost(2,3)) + 2*(cost(1,2)*cost(2,3))+(cost(1,3)*cost(2,2));
B = 2*(cost(2,3)+cost(1,3));
lambda = num2str(A ./ B);
set(handles.answer1_staticText,'String', lambda);
P1 = (lambda - cost(1,2))./(2*cost(1,3));
P2 = (lambda - cost(2,2))./(2*cost(2,3));
PT = mat2str(P1 + P2);
set(handles.answer2_staticText,'String', PT);
guidata(hObject, handles);
end
From the coding above, the answer become like this :
[11.75 11.25 11.25 11.75 10.75 11.5 12.75 12.75 13]
My question is I want to display my answer at the static text box like this:
P1 = (%answer for P1)
P2 = (%answer for P2)
P TOTAL = (%answer for PT)
Can anyone help me with the coding?
You have converted lambda to a string (using num2str), and thus, the calculation of P1 etc will produce unexpected results.
It's better to only convert to string in the display step, so these accidents won't happen.
Try this:
if size(cost,1) == 2
A = (4*Pdt*cost(1,3)*cost(2,3)) + 2*(cost(1,2)*cost(2,3))+(cost(1,3)*cost(2,2));
B = 2*(cost(2,3)+cost(1,3));
lambda = A ./ B;
set(handles.answer1_staticText,'String', num2str(lambda));
P1 = (lambda - cost(1,2))./(2*cost(1,3));
P2 = (lambda - cost(2,2))./(2*cost(2,3));
PT = P1 + P2;
set(handles.answer2_staticText,'String', num2str(PT));
guidata(hObject, handles);
end
Related
I am following the excism rust track, and I've hit a problem (I'm very, very new to rust)
This is a function to calculate the pythagorean triples of an integer:
use std::collections::HashSet;
use rayon::prelude::*;
pub fn find(sum: u32) -> HashSet<[u32; 3]> {
let a_b_plus_c: Vec<(u32; 2)> = (1_u32..(sum / 3_u32)).into_par_iter()
.filter_map(|a| {
let b_plus_c: u32 = sum - a;
let whole_number_check: Option<u32> = (b_plus_c.pow(2) - a.pow(2)).checked_rem(b_plus_c * 2);
match whole_number_check {
Some(0) => Some((a, b_plus_c)),
Some(_) => None,
None => None,
}
}).collect::<Vec<(u32; 2)>>();
a_b_plus_c.into_par_iter().filter_map(|a, b_plus_c| {
let b: u32 = (b_plus_c.pow(2) - a.pow(2))/(b_plus_c * 2);
let c: u32 = b_plus_c - b;
match b {
b if b > a => [a, b, c]
_ => None,
}}
).collect::<HashSet<[u32; 3]>>();
}
Or rather, it would be if it worked...
The current issue is in the line:
let a_b_plus_c: Vec<(u32; 2)> = (1_u32..(sum / 3_u32)).into_par_iter()
It says that it expected one of a number of symbols when parsing the type for a_b_plus_c, but found ;. From everything that I've seen (not much), this is the correct way to define a vector of tuples, each of which has two elements of type u32.
As I said, this is a learning exercise for me, so if anybody could help me out, I would be grateful for verbose and detailed answers :)
For what it's worth, as it might help you to comment on my code, this is the maths:
a + b + c = sum
a² + b² = c²
Rearrange for b:
b = ((b + c)² - a²) / (2(b + c))
So, iterate through a to get b+c, since (b+c) = sum - a
Then solve the above equation to get a, b+c, and b
Confirm that a < b
Then solve for c:
c = (b + c) - b
It should then spit them all out into a HashSet of arrays of a,b,c
You should enumerate each tuple's element type in definition. This should work:
let a_b_plus_c: Vec<(u32, u32)> = (1_u32..(sum / 3_u32)).into_par_iter()
I am trying to track down how to get to delta1 and delta2 in the R simpleLoess function that is called by the loess function.
In the simpleLoess function there is a call
z <- .C(C_loess_raw, y, x, if (no.st) 1 else weights,
if (no.st) weights * robust else 1, D, N, as.double(span),
as.integer(degree), as.integer(nonparametric), as.integer(order.drop.sqr),
as.integer(sum.drop.sqr), as.double(span * cell),
as.character(surf.stat), fitted.values = double(N),
parameter = integer(7L), a = integer(max.kd), xi = double(max.kd),
vert = double(2L * D), vval = double((D + 1L) * max.kd),
diagonal = double(N), trL = double(1L), delta1 = double(1L),
delta2 = double(1L), as.integer(surf.stat == "interpolate/exact"))
Which calls some C code which itself calls some fortran code. Then the delta1 and delta2 are just extracted as:
one.delta <- z$delta1
two.delta <- z$delta2
That is called in the c function here. That itself calls some fortran here. At this point I'm at a loss -- any suggestions on how the actual delta1 and delta2 are calculated so that I can recreate it would be very helpful...
So I have a program. And I am trying to simulate tons of moving particles with intricate moment logic that i would not want to have going on the CGP for many reasons. Of course I am then going to draw this all on the GPU.
Now originally I thought that when simulating TONS of particles that GPU delay would be a problem not the CPU. Unfortunately I am running 500 particles at a whopping 6fps :(.
I have tracked the latency down to how I send the vertices to the particle simulator. And not even the buffer creation, simply how I build the arrays. Basically I have arrays I clear every frame, and then go through for each particle in an array of particles and create arrays for each of them. And this leads to around 17500 append calls (with 500 particles). So I need a different way to do this because without building these arrays it runs at 60fps no cpu latency. Most of these append calls call a member of a struct.
Currently each particle is made based off of a class object. And it has things like position and color that are stored in structs. Would it be wroth my while to switch structs to arrays? Or perhaps I should switch everything to arrays? Obviously doing any of that would make things much harder to program. But would it be worth it?
A big problem is that I need each particle to be drawn as a capsule. Which I would make out of two dots and a thick line. Unfortunately OpenGL es 2.0 doesn't support thick lines so I have to draw it with two dots and two triangles :(. As you can see the function "calculateSquare" makes these two triangles based off to the two points. It is also very laggy, however it isn't the only problem, I will try to find a different way later.
What are your thoughts?
Note: According to xcode ram usage is only at 10 mb. However the cpu frame time is 141 ms.
Here is the code BTW:
func buildParticleArrays()
{
lineStrip = []
lineStripColors = []
lineStripsize = []
s_vertes = []
s_color = []
s_size = []
for cparticle in particles
{
let pp = cparticle.lastPosition
let np = cparticle.position
if (cparticle.frozen == true)
{
addPoint(cparticle.position, color: cparticle.color, size: cparticle.size)
}
else
{
let s = cparticle.size / 2.0
//Add point merely adds the data in array format
addPoint(cparticle.position, color: cparticle.color, size: cparticle.size)
addPoint(cparticle.lastPosition, color: cparticle.color, size: cparticle.size)
lineStrip += calculateSquare(pp, pp2: np, size: s)
for var i = 0; i < 6; i++
{
let rgb = hsvtorgb(cparticle.color)
lineStripColors.append(GLfloat(rgb.r))
lineStripColors.append(GLfloat(rgb.g))
lineStripColors.append(GLfloat(rgb.b))
lineStripColors.append(GLfloat(rgb.a))
lineStripsize.append(GLfloat(cparticle.size))
}
}
}
}
func addPoint(theObject: point, color: colorhsv, size: CGFloat)
{
let rgb = hsvtorgb(color)
s_vertes += [GLfloat(theObject.x), GLfloat(theObject.y), GLfloat(theObject.z)]
s_color += [GLfloat(rgb.r), GLfloat(rgb.g), GLfloat(rgb.b), GLfloat(rgb.a)]
s_size.append(GLfloat(size))
}
func calculateSquare(pp1: point, pp2: point, size: CGFloat) -> [GLfloat]
{
let p1 = pp1
var p2 = pp2
var s1 = point()
var s2 = point()
let center = CGPointMake((p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0)
var angle:CGFloat = 0
if ((p1.x == p2.x) && (p1.y == p2.y))
{
//They are ontop of eachother
angle = CGFloat(M_PI) / 2.0
p2.x += 0.0001
p2.y += 0.0001
}
else
{
if(p1.x == p2.x)
{
//UH OH x axis is equal
if (p1.y < p2.y)
{
//RESULT: p1 is lower so should be first
s1 = p1
s2 = p2
}
else
{
//RESULT: p2 is lower and should be first
s1 = p2
s2 = p1
}
}
else
{
//We could be all good
if (p1.y == p2.y)
{
//Uh oh y axis is equal
if (p1.x < p2.x)
{
//RESULT: p1 is left so should be first
s1 = p1
s2 = p2
}
else
{
//RESULT: p2 is to the right so should be first
s1 = p2
s2 = p1
}
}
else
{
//Feuf everything is ok
if ((p1.x < p2.x) && (p1.y < p2.y)) //First point is left and below
{
//P1 should be first
s1 = p1
s2 = p2
}
else //First point is right and top
{
//P2 should be first
s1 = p2
s2 = p1
}
}
}
angle = angle2p(s1, p2: s2)
}
if (angle < 0)
{
angle += CGFloat(M_PI) * 2.0
}
let yh = size / 2.0
let distance = dist(p1, p2: p2)
let xh = distance / 2.0
let tl = rotateVector(CGPointMake(-xh, yh), angle: angle) + center
let tr = rotateVector(CGPointMake(xh, yh), angle: angle) + center
let bl = rotateVector(CGPointMake(-xh, -yh), angle: angle) + center
let br = rotateVector(CGPointMake(xh, -yh), angle: angle) + center
let c1:[GLfloat] = [GLfloat(bl.x), GLfloat(bl.y), 0]
let c2:[GLfloat] = [GLfloat(tl.x), GLfloat(tl.y), 0]
let c3:[GLfloat] = [GLfloat(br.x), GLfloat(br.y), 0]
let c4:[GLfloat] = [GLfloat(tr.x), GLfloat(tr.y), 0]
let part1 = c1 + c2 + c3
let part2 = c2 + c3 + c4
return part1 + part2
}
Do you really need all particles in system RAM? e.g. for some physics collision calculation in relation to other objects in the scene? Otherwise you could just create one particle, send it to the GPU and do the calculations in a GPU shader.
Ok so after hours of tweaking the code for small bits in efficiency I have it running 500 particles at a fps of 28 which looks pretty smooth! I still have some ways to go. The best piece of advice had to do with allocating memory instead appending it. That saved tons of problems.
Special thanks to #Darko, #Marcelo_Cantos for coming up with the ideas that would ultimately optimize my code!
I'm not sure what it means in this context. I tried adding " 'uniformoutput',false " to the end of arrayfun, but then it got upset with the "+" operator saying "Undefined operator '+' for input arguments of type 'cell'."
I changed it to ".+" but got a parse error :( What am doing wrong?
Here is an image of the part that is broken and the error. The entire code is below in case someone would like to try running it or copy the broken part.
the whole code:
function gbp2(zi,zf)
global beam xlist ylist wi qi Ri wf qf Rf Psii Psif x n
beam = struct('E',[],'lambda',[],'w',[],'R',[],'q',[],'a',[]);
E = 1; % electric field
lambda = 1064*10^-9; % wavelength
k = 2*pi/lambda; % wave number
wi = 10^-3; % initial waist width (minimum spot size)
zr = (pi*wi^2)/lambda; % Rayleigh range
Ri = zi + zr^2/zi;
qi = 1/(1/Ri-1i*lambda/(pi*wi^2)); % initial complex beam parameter
Psii = atan(real(qi)/imag(qi)); % Gouy phase
mat = [1 zf; 0 1]; % transformation matrix
A = mat(1,1); B = mat(1,2); C = mat(2,1); D = mat(2,2);
qf = (A*qi + B)/(C*qi + D);
wf = sqrt(-lambda/pi*(1/imag(1/qf)));
Rf = 1/real(1/qf);
u = #(z, coor, mode, w, R, Psi) (2/pi)^(1/4)*sqrt(exp(1i*(2*mode+1)*Psi)/(2^mode*factorial(mode)*w))*...
hermiteH(mode,sqrt(2)*coor/w)*exp(-coor^2*(1/w^2+1i*k/(2*R))-1i*k*z);
% -------------------- ERROR IN THIS PIECE (below) ----------------------------
xlist = containers.Map('KeyType','double','ValueType','any');
ylist = containers.Map('KeyType','double','ValueType','any');
function pts(z, w, R, Psi)
xlist(z) = -2*w:10^-4:2*w;
ylist(z) = zeros(1,size(xlist(z),2));
for mode = 0:2:10
ylist(z) = ylist(z) + arrayfun(#(coor) u(z, coor, mode, w, R, Psi),xlist(z),'uniformoutput',false);
end
end
pts(zi,wi,Ri,Psii)
pts(zf,wf,Rf,Psif)
plot(xlist(zi),ylist(zi),xlist(zf),ylist(zf)) end
I tried writing a similar but simpler function and it seems to work just fine:
function test(zi, zf)
u = #(z,coor,mode) z*mode + integral(#(coor)coor,0,1);
xlist = containers.Map('KeyType','double','ValueType','any');
ylist = containers.Map('KeyType','double','ValueType','any');
function pts(z)
xlist(z) = -5:5;
ylist(z) = zeros(1,size(xlist(z),2));
for mode = 0:2:10
ylist(z) = ylist(z) + arrayfun(#(coor) u(z,coor,mode),xlist(z));
end
end
pts(zi)
pts(zf)
plot(xlist(zi),ylist(zi),xlist(zf),ylist(zf))
end
so I'm not sure what the problem is with my code.
The error message give you a big hint where to look:
Undefined operator '+' for input arguments of type 'cell'.
Error in gbp2/pts (line 36)
ylist(z) = ylist(z) + arrayfun(#(coor) u(z, coor, mode, w, R,
Psi),xlist(z).','uniformoutput',false);
From the documentation for arrayfun and the 'UniformOutput' option:
Requests that the arrayfun function combine the outputs into cell arrays B1,...,Bm. The outputs of function func can be of any size or type.
Indeed, if you check, the output of this line is a cell array:
arrayfun(#(coor) u(z, coor, mode, w, R, Psi),xlist(z),'uniformoutput',false)
You can't sum the values from the cell array directly. Here's one of several ways you can do this:
v = arrayfun(#(coor) u(z, coor, mode, w, R, Psi),xlist(z),'uniformoutput',false);
ylist(z) = ylist(z) + [v{:}];
However, I don't see why you need to used the 'UniformOutput' option or even the slow arrayfun at all. Just vectorize your function with respect to coor:
u = #(z, coor, mode, w, R, Psi)(2/pi)^(1/4)*sqrt(exp(1i*(2*mode+1)*Psi)/(2^mode*factorial(mode)*w))*...
hermiteH(mode,sqrt(2)*coor/w).*exp(-coor.^2*(1/w^2+1i*k/(2*R))-1i*k*z);
Now
ylist(z) = ylist(z) + u(z, xlist(z), mode, w, R, Psi);
Some additional suggestions: Don't use global variables – they're inefficient and there are almost always better solutions. If pts is meant to be a nested function, you're missing a closing end for the main gbp2 function. It might be a good idea to rename your variable mode so that it doesn't overload the built-in function of the same name. Psif isn't defined. And zeros(1,size(xlist(z),2)) can be written simply as zeros(size(xlist(z))).
y = find(sA);
l = y + sA;
for i=1:10
for j=1
l = l + sA;
end
y = y + length(y);
end
I would like to know how to store the value that is generated for l, for each iteration, in an array.
When I try do something like l(l) = l + sA; I obtain 'weird' results.
NOTE: PLEASE READ MY COMMENTS POSTED BELOW. THANKS!
For a complex loop, usually I do something like this:
results = zeros(expectedLength,1);
ixNextResult = 1;
for ixForLoop1 = 1:10
for ixForLoop2 = 20:30
..
results(ixNextResult) = calculationResult;
ixnextResult = ixNextResult + 1;
end
end
I'm having a hard time understanding what your code is trying to accomplish, so I'm not sure what to change. For example the snippet l(l) = l+sA does not make a lot of sens to me.
Try it like this:
y = find(sA); %This is incredibly strange! What exactly are you trying to achieve with this line?
l = y + sA;
for i=1:10
l = l + sA;
StoredL(i, :) = l;
y = y + length(y); %This line does nothing??? Why is it here?
end
I removed your inner loop as it was doing nothing, for j = 1 will only ever run once so what's the point?