I have a for loop code which I want to vectorize. Below is the initial for loop code, and the vectorized version of the code. The vectorized code isn't giving the same result as that of the parfor loop, hence I know something is wrong with the code. I would appreciate it if any member of the forum can help me review the vectorized code and see if they can point out my errors to me. Thank you in advance.
% Initialization and precomputations
% w is an n x 1 vector
% beta: any number larger than 0. Usually set to 1.
Here is the for-loop code I need to vectorize:
f = zeros(n,1);
x = w;
y = w;
rho = 1;
v = f – (rho*y);
rhow = rho*w;
n = length(w);
parfor i = 1 : n
if w(i) >= 0
if v(i) < -rhow(i) – beta – 1
x(i) = (-beta -1 -v(i))/rho;
elseif (-rhow(i) – beta – 1 <= v(i)) && (v(i) <= -rhow(i) + beta – 1)
x(i) = w(i);
elseif (-rhow(i) + beta – 1 < v(i)) && (v(i) < beta – 1)
x(i) = (beta – 1 -v(i))/rho;
elseif (beta – 1 <= v(i)) && (v(i) <= beta + 1)
x(i) = 0;
else
x(i) = (beta + 1 – v(i))/rho;
end
else
if v(i) < -beta -1
x(i) = (-beta -1 – v(i))/rho;
elseif (-beta – 1 <= v(i) )&& (v(i) <= -beta + 1)
x(i) = 0;
elseif (-beta + 1 < v(i)) && (v(i) < -rhow(i) – beta + 1)
x(i) = (-beta + 1 – v(i))/rho;
elseif (-rhow(i) – beta + 1 <= v(i)) && (v(i) <= -rhow(i) + beta + 1)
x(i) = w(i);
else
x(i) = (beta + 1 – v(i))/rho;
end
end
end
======================================================================
And here is my vectorized version of the code above:
cond1 = (w >= 0);
cond2 = (w >= 0) & (v < -rhow-beta-1);
x(cond2) = (-beta-1-v(cond2))/rho;
cond3 = (w>=0)&(-rhow - beta -1 <= v) & (v <= -rhow + beta - 1);
x(cond3) = w(cond3);
cond4 = (w>=0) & (-rhow +beta - 1 < v) & (v < beta - 1);
x(cond4) = (beta - 1 - v(cond4))/rho;
cond5 = (w>=0) & (beta - 1 <= v) & (v <= beta + 1);
x(cond5) = 0;
cond6 = (~cond2);
x(cond6) = (beta + 1 - v(cond6))/rho;
cond7 = ((~cond1) & v < -beta -1);
x(cond7) = (-beta -1 - v(cond7))/rho;
cond8 = ((~cond1) & (-beta - 1 <= v) & (v <= -beta + 1));
x(cond8) = 0;
cond9 = ((~cond1) & (-beta + 1 < v) & (v < -rhow - beta + 1));
x(cond9) = (-beta + 1 - v(cond9))/rho;
cond10 = ((~cond1) & (-rhow - beta + 1 <= v) & (v <= -rhow + beta + 1));
x(cond10) = w(cond10);
cond11 = (~cond1);
x(cond11) = (beta + 1 - v(cond11))/rho;
I'm adding another answer with all the conditionals checked:
cond1 = (w >= 0);
cond2 = cond1 & (v < -rhow – beta – 1);
cond3 = cond1 & ((-rhow – beta – 1 <= v) && (v <= -rhow + beta – 1));
cond4 = cond1 & ((-rhow + beta – 1 < v) && (v < beta – 1));
cond5 = cond1 & ((beta – 1 <= v) && (v <= beta + 1));
cond6 = cond1 & (v > beta + 1)
cond7 = ~cond1 & (v < -beta -1);
cond8 = ~cond1 & ((-beta – 1 <= v ) && (v <= -beta + 1));
cond9 = ~cond1 & ((-beta + 1 < v) && (v < -rhow – beta + 1));
cond10 = ~cond1 & ((-rhow – beta + 1 <= v) && (v <= -rhow + beta + 1));
cond11 = ~cond1 & (v > -rhow + beta + 1);
x(cond2)=... to x(cond11)=... remain the same.
Hope this works.
Here is one mistake, cond6 is not equivalent to the original first else
cond2 = (w >= 0) & (v < -rhow-beta-1);
cond6 = (~cond2);
x(cond6) = (beta + 1 - v(cond6))/rho;
in the original this is:
if w(i) >= 0
if v(i) < -rhow(i) – beta – 1
...
else
x(i) = (beta + 1 – v(i))/rho; %this should be cond6
end
end
The else should be evaluated like this (If I'm not mistaken)
x(cond1) = (beta + 1 - v(cond6))/rho;
and before all the others up to cond5.
I did not check all the code, so if this doesn't solve your problem let me know.
Related
Following up on a previous question, I have code that I think should limit the number of randomly generated points in each quadrant of the total tile; however, it is not working.
n = 4;
used = [];
k = 0;
a1_count = 0;
a2_count = 0;
a3_count = 0;
a4_count = 0;
min = 1;
max = 1;
while k<n
x = rand*2;
y = rand*2;
notvalid = 0;
if (0 <= x) && (x <= 1) && (0 <= y) && (y <= 1)
a1_count = a1_count + 1;
end
if (1 < x) && (x <= 2) && (0 <= y) && (y <= 1)
a2_count = a2_count + 1;
end
if (0 <= x) && (x <= 1) && (1 < y) && (y <= 2)
a3_count = a3_count + 1;
end
if (1 < x) && (x <= 2) && (1 < y) && (y <= 2)
a4_count = a4_count + 1;
end
%%%
if (min <= a1_count) && (a1_count <= max) && (min <= a2_count) && (a2_count <= max)...
&& (min <= a3_count) && (a3_count <= max) && (min <= a4_count) && (a4_count <= max)
notvalid=1;
end
if notvalid
continue
end
used(end+1,:) = [x;y];
k = k+1;
end
I wish to generate 4 random points, and have one in each quadrant of the total area. To do this, I have a maximum and minimum number of points in each quadrant (in this case 1), and an if statement to check that the count for each tile falls within the min and max. If it doesn't, then notvalid = 0 and the loop should begin again. This function doesn't seem to work however, as the loop finishes with 4 points total and is completely random (all the counts should = 1).
Can anyone spot where I'm going wrong?
I may be missing something, but the easiest approach would probably be something like
Select N random numbers within the x/y range of the first grid cell
Repeat for all grid cells
Here is some basic code that should create N random x/y points per grid cell
% Define the grid (for demonstration purposes)
dx = 1; dy = 1;
xrange = 0:dx:2;
yrange = 0:dy:2;
% Number of points per cell
N = 1;
[lowerx, lowery] = meshgrid(xrange(1:end-1), yrange(1:end-1));
% Store all those random numbers in a cell
data = cell(size(lowerx));
for k = 1:numel(lowerx);
% Generate 4 random points within the x/y range
xcoord = (rand(N, 1) * dx) + lowerx(k);
ycoord = (rand(N, 1) * dy) + lowery(k);
data{k} = [xcoord, ycoord];
end
disp(data)
data =
[1x2 double] [1x2 double]
[1x2 double] [1x2 double]
EDIT
To address your question directly using the code that you have provided, the logic in the code in your question is a little wonky. I have rewritten your while loop to be a little clearer so we can talk through it.
while k < n
x = rand * 2;
y = rand * 2;
if y >= 0 && y < 1
if x >= 0 && x < 1
a1_count = a1_count + 1;
else
a2_count = a2_count + 1;
end
else
if x >= 0 && x < 1
a3_count = a3_count + 1;
else
a4_count = a4_count + 1;
end
end
counts = [a1_count, a2_count, a3_count, a4_count];
notValid = all(counts >= minimum) && all(counts <= maximum);
if notValid
continue;
end
used(end+1,:) = [x;y];
k = k+1;
end
So the biggest thing is your notValid check. If you actually look at what you're checking (that all your *_count variables are within the pre-specified limits), I believe that if all of those conditions are true, then the current point is valid; however you state just the opposite.
Then you basically say, that if the current x y is valid, then add it to the used list. Well this logic is fine except that you define validity backwards as I stated before.
Ok so that aside, let's look at when you think that a point is not valid. Well, then you (correctly) go to the next iteration, but you never decrement the *_count variable. So say you had 1 point in quadrant 1 already and the second iteration through the loop it's in quadrant 1 again. Well you'd add 1 to a1_count and then see that it isn't valid (a1_count exceeds max) and go to the next loop, but a1_count stays at 2 despite really only having 1 because you just rejected it.
Now, all of that aside. Let's consider the first time through your loop and look at your validity check. Since you only add one point. Your validity check can never pass (if implemented correctly) because all *_count variables except the one that was just incremented will be less than the min.
So I think what happened is you probably did the validity check correctly at first, ended up with an infite while loop, and then negated that check, didn't get an infinite loop, but as a result got an incorrect solution.
The solution that you are getting currently, is literally the first 4 times through the while loop due to the incorrect logic.
If you really like your current approach, we can clean up the code to be correct.
n = 4;
used = zeros(0,2);
minimum = 1;
maximum = 1;
counts = [0 0 0 0];
while true
x = rand * 2;
y = rand * 2;
if y >= 0 && y < 1
if x >= 0 && x < 1
quadrant = 1;
else
quadrant = 2;
end
else
if x >= 0 && x < 1
quadrant = 3;
else
quadrant = 4;
end
end
% Check to see if we can even add this point
if counts(quadrant) + 1 > maximum
continue;
end
counts(quadrant) = counts(quadrant) + 1;
used = cat(1, used, [x, y]);
isComplete = all(counts >= minimum & counts <= maximum) && ...
size(used, 1) == n;
if isComplete
break
end
end
I am struggling to convert a function, which I require for my civil engineering project, from symbolic expression. I need to use fzero to find the root of the function. Here H should be the variable and I need to find out the value of H. The function goes like
function x_c = f_x_c(s,H0,VA,Lo,qc,EAo,NF,Sj,Fj)
if (s < 0) || (s > Lo)
disp('The value of s is invalid')
disp(['s = ' num2str(s)]);
return
end
C1 = H/qc;
if NF == 0
n = 0;
sn = 0;
sum_Fj = 0;
end
if NF >= 1
Sj_Q = [0; Sj; Lo];
%Determine n and sn if 0 <= s < Lo:
if s < Lo
STOP = 0;
k = 0;
while STOP == 0
k = k + 1;
if (s >= Sj_Q(k,1)) && (s < Sj_Q((k + 1),1))
STOP = 1;
end
end
n = k - 1;
sn = Sj_Q(k,1);
end
%Determine n and sn if s = Lo:
if s == Lo
n = NF;
sn = Sj(NF,1);
end
sum_Fj = sum(Fj(1:n,1));
end
x_c = (H/EAo)*s;
x_c = x_c + C1*asinh((qc*s - VA + sum_Fj)/H) + ...
- C1*asinh((qc*sn - VA + sum_Fj)/H);
for j = 1:n
sk = Sj_Q((j + 1),1);
sk_1 = Sj_Q(j,1);
sum_Fj = sum(Fj(1:(j - 1)));
x_c = x_c + ...
+ C1*asinh((qc*sk - VA + sum_Fj)/H) + ...
- C1*asinh((qc*sk_1 - VA + sum_Fj)/H);
end
I want to use this f_x_c.m file in the main file where I will find the roots of this equation.
Could someone guide me how I can do that?
I have tried doing it using the following code but I wasn't successful.
if (s < 0) || (s > Lo)
disp('The value of s is invalid')
disp(['s = ' num2str(s)]);
return
end
C1 = #(H) (H/qc);
if NF == 0
n = 0;
sn = 0;
sum_Fj = 0;
end
if NF >= 1
Sj_Q = [0; Sj; Lo];
%Determine n and sn if 0 <= s < Lo:
if s < Lo
STOP = 0;
k = 0;
while STOP == 0
k = k + 1;
if (s >= Sj_Q(k,1)) && (s < Sj_Q((k + 1),1))
STOP = 1;
end
end
n = k - 1;
sn = Sj_Q(k,1);
end
%Determine n and sn if s = Lo:
if s == Lo
n = NF;
sn = Sj(NF,1);
end
sum_Fj = sum(Fj(1:n,1));
end
x_c =#(H) (H/EAo)*s;
x_c =#(H) (x_c(H) + (C1(H))*asinh((qc*s - VA + sum_Fj)/H) + ...
- (C1(H))*asinh((qc*sn - VA + sum_Fj)/H));
for j = 1:n
sk = Sj_Q((j + 1),1);
sk_1 = Sj_Q(j,1);
sum_Fj = sum(Fj(1:(j - 1)));
x_c =#(H) (x_c(H) + ...
+ C1(H)*asinh((qc*sk - VA + sum_Fj)/H) + ...
- C1(H)*asinh((qc*sk_1 - VA + sum_Fj)/H));
end
Edit:
I want to solve the following equation in the main file:
equation = f_x_c(inext_length, H0, vertical_reaction, inext_length, qc, EAo, NF, hanger_arc_length, point_hanger_force) + 1400;
% Whatever equation f_x_c returns, I have to add another number to it(like here it is 1400), then solve this equation using fzero.
So, in the main file, I wrote like:
equation = #(H) f_x_c(inext_length, H0, vertical_reaction, inext_length, qc, EAo, NF, hanger_arc_length, point_hanger_force);
equation = #(H) (equation(H) + 1400);
answer = fsolve(equation, H0);
A mock answer to your question probably looks like
function x_c = f_x_c(H,A,B,C,D)
x_c = H*A;
x_c = x_c + B*asinh(C/H) - B*asinh(D/H);
end
and a call to solver is
H = fzero(#(H)(f_x_c(H,1,1,1,1)+1400),1);
I am trying to plot a best fit line on a probability density function with logarithmic axes. The Y-axis (PDF) is 10^-12 to 10^-28, while the X-axis is 10^10 to 10^20. I've tried polyfit, with no luck. Any ideas? Attached is my code.
Thanks,
Kevin
clc;
clear all;
load Aug2005_basin_variables.mat
% Initialize
j_len = length(W_SH);
prob_dens_all = zeros(j_len,30);
ii = 1 : j_len;
count(1:30) = 0;
bin(1:30) = 0;
for i = 1 : 30
bin(i) = 10^(11 + (0.3*i));
end
% Bin the Watts
for i = 1 : j_len
if((log10(W_SH(i)) >= 11) && (log10(W_SH(i)) < 11.3))
count(1) = count(1) + 1;
end
if((log10(W_SH(i)) >= 11.3) && (log10(W_SH(i)) < 11.6))
count(2) = count(2) + 1;
end
if((log10(W_SH(i)) >= 11.6) && (log10(W_SH(i)) < 11.9))
count(3) = count(3) + 1;
end
if((log10(W_SH(i)) >= 11.9) && (log10(W_SH(i)) < 12.2))
count(4) = count(4) + 1;
end
if((log10(W_SH(i)) >= 12.2) && (log10(W_SH(i)) < 12.5))
count(5) = count(5) + 1;
end
if((log10(W_SH(i)) >= 12.5) && (log10(W_SH(i)) < 12.8))
count(6) = count(6) + 1;
end
if((log10(W_SH(i)) >= 12.8) && (log10(W_SH(i)) < 13.1))
count(7) = count(7) + 1;
end
if((log10(W_SH(i)) >= 13.1) && (log10(W_SH(i)) < 13.4))
count(8) = count(8) + 1;
end
if((log10(W_SH(i)) >= 13.4) && (log10(W_SH(i)) < 13.7))
count(9) = count(9) + 1;
end
if((log10(W_SH(i)) >= 13.7) && (log10(W_SH(i)) < 14.0))
count(10) = count(10) + 1;
end
if((log10(W_SH(i)) >= 14.0) && (log10(W_SH(i)) < 14.3))
count(11) = count(11) + 1;
end
if((log10(W_SH(i)) >= 14.3) && (log10(W_SH(i)) < 14.6))
count(12) = count(12) + 1;
end
if((log10(W_SH(i)) >= 14.6) && (log10(W_SH(i)) < 14.9))
count(13) = count(13) + 1;
end
if((log10(W_SH(i)) >= 14.9) && (log10(W_SH(i)) < 15.2))
count(14) = count(14) + 1;
end
if((log10(W_SH(i)) >= 15.2) && (log10(W_SH(i)) < 15.5))
count(15) = count(15) + 1;
end
if((log10(W_SH(i)) >= 15.5) && (log10(W_SH(i)) < 15.8))
count(16) = count(16) + 1;
end
if((log10(W_SH(i)) >= 15.8) && (log10(W_SH(i)) < 16.1))
count(17) = count(17) + 1;
end
if((log10(W_SH(i)) >= 16.1) && (log10(W_SH(i)) < 16.4))
count(18) = count(18) + 1;
end
if((log10(W_SH(i)) >= 16.4) && (log10(W_SH(i)) < 16.7))
count(19) = count(19) + 1;
end
if((log10(W_SH(i)) >= 16.7) && (log10(W_SH(i)) < 17.0))
count(20) = count(20) + 1;
end
if((log10(W_SH(i)) >= 17.3) && (log10(W_SH(i)) < 17.6))
count(21) = count(21) + 1;
end
if((log10(W_SH(i)) >= 17.6) && (log10(W_SH(i)) < 17.9))
count(22) = count(22) + 1;
end
if((log10(W_SH(i)) >= 17.9) && (log10(W_SH(i)) < 18.2))
count(23) = count(23) + 1;
end
if((log10(W_SH(i)) >= 18.2) && (log10(W_SH(i)) < 18.5))
count(24) = count(24) + 1;
end
if((log10(W_SH(i)) >= 18.5) && (log10(W_SH(i)) < 18.8))
count(25) = count(25) + 1;
end
if((log10(W_SH(i)) >= 18.8) && (log10(W_SH(i)) < 19.1))
count(26) = count(26) + 1;
end
if((log10(W_SH(i)) >= 19.1) && (log10(W_SH(i)) < 19.4))
count(27) = count(27) + 1;
end
if((log10(W_SH(i)) >= 19.4) && (log10(W_SH(i)) < 19.7))
count(28) = count(28) + 1;
end
if((log10(W_SH(i)) >= 19.7) && (log10(W_SH(i)) < 20.0))
count(29) = count(29) + 1;
end
if((log10(W_SH(i)) >= 20.0) && (log10(W_SH(i)) < 20.3))
count(30) = count(30) + 1;
end
end
for i=1:30
prob(i) = count(i)/sum(count);
prob_dens(i) = prob(i)/bin(i);
end
% Check
sum(prob_dens.*bin);
prob_dens_all(i,:) = prob_dens(:);
%end
prob_dens_mean = zeros(1,30);
for i = 1 : 30
prob_dens_mean(1,i) = mean(prob_dens_all(:,i));
%prob_dens_std(1,i) = std(prob_dens_all(:,i));
end
% Plot
best_fit = polyfit(bin,log10(prob_dens_mean),11)
h = figure;
loglog(bin,prob_dens_mean,'ro','MarkerSize',10)
hold on;
plot(best_fit,'b')
t = title('Event Power Distribution, SHem, August 2005');
set(t, 'FontWeight', 'bold', 'FontSize', 12)
set(gca, 'FontWeight', 'bold', 'FontSize', 12)
xlabel('Event Power (W)');
ylabel('Probability Density');
print -dpng SHem_Wattage_PDF_AUG2005.png
I don't have your data, but here is an example using some random normally-distributed random data
x=randn(1000,1)+5; % create some data, keep numbers positive by adding 5
[n,xb]=hist(x); % Create the histogram
n = n/sum(n); % convert counts to a pdf
p=polyfit(log(xb), log(n), 3); % Do a 3rd order fit
loglog(xb,n, '*-', xb, exp(polyval(p, log(xb))), 'r')
grid on
legend('PDF', 'Fit', 0)
I am having a hard time plotting a step function. The function involves is the Haar scaling function which is defind as:
ø(x) = 1 if 0 ≤ x < 1
ø(x) = 0 otherwise
I am supposed to plot the following function:
f(x) = 2ø(4x) + 2ø(4x - 1) + ø(4x - 2) - ø(4x - 3)
This is supposed to give me a plot where f = 2 on the interval 0 ≤ x < 0.5; f = 1 on the interval 0.5 ≤ x < 0.75; f = -1 on the interval 0.75 ≤ x < 1, and f = zero otherwise.
I tried the following code:
f = #(t) 2*(4*t > 0) + 2*(4*t > 1) + (4*t > 2) - (4*t > 3);
t = linspace(-2,2,100);
stairs(t,f(t))
However, this does not give me an accurate graph. So what am I doing wrong here? Any help will be greatly appreciated!
Your implementation of f only deals with half of your specification of phi.
f = #(t) 2*(4*t > 0) + 2*(4*t > 1) + (4*t > 2) - (4*t > 3);
In each of the terms applies the inequality 0 < X, rather than 0 <= X. Also nothing is done about the X < 1 inequality.
Rather than trying to make a custom version for each term, why not code up your formula directly?
phi = #(x) x >= 0 & x < 1;
f = #(x) 2*phi(4*x) + 2*phi(4*x-1) + phi(4*x - 2) - phi(4*x - 3);
it should be:
f = #(t) 2*(4*t > 0 & 4*t < 1) + 2*(4*t > 1 & 4*t < 2) + (4*t > 2 & 4*t < 3) - (4*t > 3);
Because every segment should be defined precisely with start and end values.
I'm trying to make a B-Spline Function
first i set the variables and made the Knot vector
# cmpp.m
% Set variables
k = 3; % (8 mod 2 + 2 + 1)
p = k - 1; % Order = 2
n = 2*k - 1; % Control points = 5
l = n + p + 1; % Vector size n + p + 1 = 8
% Create the Knot vector
% Kv = [0 0 0 1 2 3 3 3] size = 8
knoten = 0; % set all knots to 0
Kv = [];
for j=1:1:l
Kv = [ Kv 0 ];
end
for i=1:1:l
if (i > n)
if (i <= n)
Kv(i) = knoten + 1;
knoten = knoten + 1;
else
Kv(i) = knoten;
end
else
Kv(i) = knoten;
end
end
then i worte a function to create the basic function
# f.m
function N = f(N,t,i,k,u,x,s)
if (u < x)
N(i,k) = ((((u-t(i)).*f(t,i,k-1,u+s,x,s)) / (t(i+k-1) - t(i))) + (((t(i+k)-u).*f(t,i+1,k-1,u+s,x,s)) / (t(i+k) - t(i+1))));
if ((u >= t(i)) && (u < t(i+1)))
N(i,1) = 1;
else
N(i,1) = 0;
end
end
end
and called it in cmpp.m
# cmpp.m
...
...
...
N = zeros(l,k);
x = (n+1) - (k-1);
s = 1;
N = [N f(N,Kv,1,k,0,x,s)];
but i get always this error in Matlab
>> cmpp
Subscripted assignment dimension mismatch.
Error in f (line 3)
N(i,k) = ((((u-t(i)).*f(t,i,k-1,u+s,x,s)) / (t(i+k-1) - t(i))) +
(((t(i+k)-u).*f(t,i+1,k-1,u+s,x,s)) / (t(i+k) - t(i+1))));
Error in cmpp (line 32)
N = [N f(N,Kv,1,k,0,x,s)]