I'm trying to implement an inversion counter in MATLAB using MergeSort, but for some reason, some of the answers are way off. For example, the number of inversions in [3, 4, 8, 1] is 3, but I'm getting 2. However, the array is being sorted correctly, so I think that the way that I'm counting the split inversions is the problem.
Here's my code:
function [count, sorted] = mergesort(A)
% count is the number of inversions; sorted is the sorted array.
n = length(A);
if n == 1
count = 0;
sorted = A;
else
m = ceil(n/2);
[count1, sorted1] = mergesort(A(1:m));
[count2, sorted2] = mergesort(A(m+1:n));
[crosscount, sorted] = merge(sorted1, sorted2);
count = count1 + count2 + crosscount;
end
end
function [crosscount, z] = merge(x, y)
n = length(x); m = length(y); z = zeros(1, n+m);
ix = 1;
iy = 1;
crosscount = 0;
for iz = 1:(n+m);
if ix > n
z(iz) = y(iy);
iy = iy + 1;
elseif iy > m
z(iz) = x(ix);
ix = ix + 1;
crosscount = crosscount + (n + 1 - ix); %this might be wrong
elseif x(ix) <= y(iy)
z(iz) = x(ix);
ix = ix + 1;
elseif x(ix) > y(iy)
z(iz) = y(iy);
iy = iy + 1;
crosscount = crosscount + 1; %im pretty sure this is right
end
end
end
Alright, so a friend helped me figure it out. My intuition was correct, but I needed help from an actual programmer to understand where I went wrong:
elseif iy > m
z(iz) = x(ix);
ix = ix + 1;
crosscount = crosscount + (n + 1 - ix); **%this might be wrong - this is actually wrong, since you don't want to count if you're traversing beyond the edge of the right array, and since the actual counting is happening in the last if case**
elseif x(ix) <= y(iy)
z(iz) = x(ix);
ix = ix + 1;
elseif x(ix) > y(iy)
z(iz) = y(iy);
iy = iy + 1;
crosscount = crosscount + **(n + 1 - ix)** **this is right because you're counting the remaining numbers in your left array that are also greater than y(iy) and just adding that to your count**
end
Related
I want the function P to look like this:
-1 + 0.6366*(x+pi/2) + (-0.000)*(x + pi/2)*(x)
and right now it looks like this
(5734161139222659*x)/9007199254740992 + (5734161139222659*pi)/18014398509481984 - (8131029572207409*x*(x + pi/2))/324518553658426726783156020576256 - 1.
How to convert S array so that the values are not symbolic?
syms P x
f = sin(x);
f = matlabFunction(f);
X = [-pi/2, 0, pi/2];
Y = f(sym(X));
P = MetN(X,Y,x)
P = matlabFunction(P);
function [P] = MetN(X,Y,x)
n = length(X);
for i = 1:n
A(i,1) = 1;
end
for i = 2:n
for j = 2: n
if i >= j
produs = 1;
for k =1:j-1
produs = produs * (X(i) - X(k));
end
A(i,j) = produs;
end
end
end
S = SubsAsc(A, Y);
S = double(S);
disp(S);
sym produs
P = double(sym(S(1)));
for i = 2:n
produs = 1;
for j = 1:i-1
produs = produs * (x - sym(X(j)));
end
disp(produs);
P = P + double(S(i))*produs;
end
end
function [x] = SubsAsc(A,b)
n = length(b);
x(1) = (1/A(1,1))*b(1);
for k = 2:n
s = 0;
for j = 1:k-1
s = s + A(k,j)*x(j);
end
x(k) = (1/A(k,k))*(b(k)-s);
end
end
The output you currently have is because symbolic uses exact arithmetic, so it outputs it as a rational number (hence the ugly fraction).
To have it output P using decimals, use vpa(). For instance output P using decimals to 5 significant digits
>> vpa(P, 5)
ans =
0.63662*x - 2.5056e-17*x*(x + 1.5708)
This will, however, also round pi, so you can't really have the best of both worlds here.
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 unable to get converging values using a Gauss-Seidel algorithm
Here is the code:
A = [12 3 -5 2
1 6 3 1
3 7 13 -1
-1 2 -1 7];
b = [2
-3
10
-11];
ep = 1e-8;
[m, n] = size(A);
[n, p] = size(b);
x = zeros(n, 1001);
x(:, 1) = []
for k=0:1000
ka = k + 1;
if ka == 1001
break;
end
xnew = zeros(n,1);
for i=1:n
sum = 0;
j = 1;
while j < i
s1 = s1 + A(i,j) * x(j, ka + 1);
j = j + 1;
end
j = i + 1;
while j <= n
sum = sum + A(i,j) * x(j, ka);
j = j + 1;
end
xnew(i) = (b(i) - sum) / A(i, i);
% if result is within error bounds exit loop
if norm(b - A * xnew, 2) < ep * norm(b, 2)
'ending'
break
end
end
x(:,ka + 1) = xnew;
end
I cannot get the A * xnew to converge on b what am I doing wrong?
I have tried running this changing the syntax several times, but I keep getting values that are way off.
Thanks!
Gabe
You have basically two problems with your code:
(1) You are using two different variables "sum" and "s1". I replaced it by mySum. By the way, dont use "sum", since there is a matlab function with this name.
(2) I think there is also a problem in the update of x;
I solved this problem and I also tried to improve your code:
(1) You dont need to save all "x"s;
(2) It is better to use a "while" than a for when you dont know how many iterations you need.
(3) It is good to use "clear all" and "close all" in general in order to keep your workspace. Sometimes old computations may generate errors. For instance, when you use matrices with different sizes and the same name.
(4) It is better to use dot/comma to separate the lines of the matrices
You still can improve this code:
(1) You can test if A is square and if it satisfies the conditions necessary to use this numerical method: to be positive definite or to be diagonally dominant.
clear all
close all
A = [12 3 -5 2;
1 6 3 1;
3 7 13 -1;
-1 2 -1 7];
b = [2;
-3;
10;
-11];
ep = 1e-8;
n = length(b); % Note this method only works for A(n,n)
xNew=zeros(n,1);
xOld=zeros(n,1);
leave=false;
while(~leave)
xOld=xNew;
for i=1:n
mySum = 0;
j = i + 1;
while j <= n
mySum = mySum + A(i,j) * xOld(j,1);
j = j + 1;
end
j = 1;
while j < i
mySum = mySum + A(i,j) * xNew(j,1);
j = j + 1;
end
mySum=b(i,1)-mySum;
xNew(i,1) = mySum / A(i, i);
end
if (norm(b - A * xNew, 2) < ep * norm(b, 2))
disp('ending');
leave=true;
end
xOld = xNew;
end
xNew
I have a vector. I want to remove outliers. I got bin and no of values in that bin. I want to remove all points based on the number of elements in each bin.
Data:
d1 =[
360.471912914169
505.084636471948
514.39429429184
505.285068055647
536.321181755858
503.025854206322
534.304229816684
393.387035881967
396.497969729985
520.592172434431
421.284713703215
420.401106087984
537.05330275495
396.715779872694
514.39429429184
404.442344469518
476.846474245118
599.020867750031
429.163139144079
514.941744277933
445.426761656729
531.013596812737
374.977332648255
364.660115724218
538.306752697753
519.042387479096
1412.54699036882
405.571202133485
516.606049132218
2289.49623498271
378.228766753667
504.730621222846
358.715764917016
462.339366699398
512.429858614816
394.778786157514
366
498.760463549388
366.552861126468
355.37022947906
358.308526273099
376.745272034036
366.934599077274
536.0901883079
483.01740134285
508.975480745389
365.629593988233
536.368800360349
557.024236456548
366.776498701866
501.007025898839
330.686029339009
508.395475983019
429.563732174866
2224.68806802212
534.655786464525
518.711297351426
534.304229816684
514.941744277933
420.32368479542
367.129404978681
525.626188464768
388.329756778952
1251.30895065927
525.626188464768
412.313764019587
513.697381733643
506.675438520558
1517.71183364959
550.276294237722
543.359917550053
500.639590923451
395.129864728041];
Histogram computation:
[nelements,centers] = hist(d1);
nelements=55 13 0 0 1 1 1 0 0 2
I want to remove all points apearing less than 5 (in nelements). It means only first 2 elements in nelements( 55, 13 ) remains.
Is there any function in matlab.
You can do it along these lines:
threshold = 5;
bin_halfwidth = (centers(2)-centers(1))/2;
keep = ~any(abs(bsxfun(#minus, d1, centers(nelements<threshold))) < bin_halfwidth , 2);
d1_keep = d1(keep);
Does this do what you want?
binwidth = centers(2)-centers(1);
centersOfRemainingBins = centers(nelements>5);
remainingvals = false(length(d1),1);
for ii = 1:length(centersOfRemainingBins )
remainingvals = remainingvals | (d1>centersOfRemainingBins (ii)-binwidth/2 & d1<centersOfRemainingBins (ii)+binwidth/2);
end
d_out = d1(remainingvals);
I don't know Matlab function for this problem, but I think, that function with follow code is what are you looking for:
sizeData = size(data);
function filter_hist = filter_hist(data, binCountRemove)
if or(max(sizeData) == 0, binCountRemove < 1)
disp('Error input!');
filter_hist = [];
return;
end
[n, c] = hist(data);
sizeN = size(n);
intervalSize = c(2) - c(1);
if sizeData(1) > sizeData(2)
temp = transpose(data);
else
temp = data;
end
for i = 1:1:max(sizeN)
if n(i) < binCountRemove
a = c(i) - intervalSize / 2;
b = c(i) + intervalSize / 2;
sizeTemp = size(temp);
removeInds = [];
k = 0;
for j = 1:1:max(sizeTemp)
if and(temp(j) > a, less_equal(temp(j), b) == 1)
k = k + 1;
removeInds(k) = j;
end
end
temp(removeInds) = [];
end
end
filter_hist = transpose(temp);
%Determines when 'a' less or equal to 'b' by accuracy
function less_equal = less_equal(a, b)
delta = 10^-6; %Accuracy
if a < b
less_equal = 1;
return;
end
if abs(b - a) < delta
less_equal = 1;
return;
end
less_equal = 0;
You can do something like this
nelements=nelements((nelements >5))
I have the following error in MATLAB:
??? Subscript indices must either be real positive integers or
logicals.
Error in ==> Lloyd_Max at 74 D(w_count) = mean((x -
centers(xq)).^2);
This is my code :
function [ xq,centers,D ] = Lloyd_Max( x,N,min_value,max_value )
%LLOYD_MAX Summary of this function goes here
% Detailed explanation goes here
x = x';
temp = (max_value - min_value)/2^N;
count=1;
for j=0:temp:((max_value - min_value)-temp),
centers(count) = (j + j + temp )/2;
count = count + 1;
end
for i=1:length(centers),
k(i) = centers(i);
end
w_count = 0;
while((w_count < 2) || (D(w_count) - D(w_count - 1) > 1e-6))
w_count = w_count + 1;
count1 = 2;
for i=2:(count-1),
T(i) = (k(i-1) + k(i))/2;
count1 = count1 +1 ;
end
T(1) = min_value;
T(count1) = max_value;
index = 1;
for j=2:count1,
tempc = 0;
tempk = 0;
for k=1:10000,
if(x(k) >= T(j-1) && x(k) < T(j))
tempk = tempk + x(k);
tempc = tempc + 1;
end
end
k(index) = tempk;
k_count(index) = tempc;
index = index + 1;
end
for i=1:length(k),
k(i) = k(i)/k_count(i);
end
for i=1:10000,
if (x(i) > max_value)
xq(i) = max_value;
elseif (x(i) < min_value)
xq(i) = min_value;
else
xq(i) = x(i);
end
end
for i=1:10000,
cnt = 1;
for l=2:count1,
if(xq(i) > T(l-1) && xq(i) <= T(l))
xq(i) = cnt;
end
cnt = cnt +1 ;
end
end
D(w_count) = mean((x - centers(xq)).^2);
end
end
and i call it and have these inputs :
M = 10000
t=(randn(M,1)+sqrt(-1)*randn(M,1))./sqrt(2);
A= abs(t).^2;
[xq,centers,D] = Lloyd_Max( A,2,0,4 );
I tried to comment the while and the D, Results :
I got the xq and the centers all normal, xq in the 1-4 range, centers 1-4 indexes and 0.5-3.5 range.
I dont know whats going wrong here...Please help me.
Thank in advance!
MYSTERY SOVLED!
Thank you all guys for your help!
I just putted out of the while the for loop :
for i=1:10000,
if (x(i) > max_value)
xq(i) = max_value;
elseif (x(i) < min_value)
xq(i) = min_value;
else
xq(i) = x(i);
end
end
and it worked like charm.... this loop was initilizing the array again. Sorry for that. Thank you again!
There is an assignment xq(i) = x(i) somewhere in the middle of your function, but you pass A as x from outside where you calculate A from t which is sampled by randn, so you can't promise xq is an integer.
I'm not sure exactly what you are aiming to do, but your vector xq does not contain integers, it contains doubles. If you want to use a vector of indices as you do with centers(xq), all elements of the vector need to be integers.
Upon a little inspection, it looks like xq are x values, you should find some way to map them to the integer of the closest cell to which they belong (i'm guessing 'centers' represents centers of cells?)