Related
I am trying to implement this alghoritm for finding a new constraint:
In my case we take only 3 natural numbers i.e 1,2, 3.
The sets associated with those natural numbers are M1, M2 and M3. Instead of the Newton Method in II(2), I chose a solver provided by Matlab fmincon.
Here is my code that is not working!
function[s_new]= checking2(M1,M2,M3,x)
M1=linspace(0,1,10)';
M2=linspace(0,1,100)';
M3=linspace(0,1,1000)';
bool1=0;
eta = 10^-8;
pocz=[];
max=-100;
x = [0.1,0.1]'; % warunek początkowy
A = [];
b = [];
Aeq = [];
beq = [];
Set=[0,1];
g = #(x,s) 5*x(1).^2.*sin(pi.*sqrt(s))./(1+s.^2) - x(2);
g_new = #(s) -g(x,s);
for i=1:length(M1)
if g(x,M1(i,:))>eta
s_new=M1(i,:);
bool1=1;
end
end
if ~bool1
for i=1:length(M1)
if g(x,M1(i,:))>max
pocz=M1(i,:);
max=g(x,M1(i,:));
end
end
if max<-eta
bool1=1;
end
end
if ~bool1
s_maybe = fmincon(g_new,pocz,A,b,Aeq,beq,min(Set),max(Set));
if g(x,s_maybe)>eta
s_new=s_maybe;
bool1=1;
end
end
if ~bool1
for i=1:length(M2)
if g(x,M2(i,:))>eta
s_new=M2(i,:);
bool1=1;
end
end
end
if ~bool1
for i=1:length(M2)
if g(x,M2(i,:))>max
pocz=M2(i,:);
max=g(x,M2(i,:));
end
end
if max<-eta
bool1=1;
end
end
if ~bool1
s_maybe = fmincon(g_new,pocz,A,b,Aeq,beq,min(Set),max(Set));
if g(x,s_maybe)>eta
s_new=s_maybe;
bool1=1;
end
end
if ~bool1
for i=1:length(M3)
if g(x,M3(i,:))>eta
s_new=M3(i,:);
bool1=1;
end
end
end
if ~bool1
s_new = 1;
end
disp(s_new);
The problem is:
Undefined function or variable 's_new'.
Error in checking2 (line 70)
disp(s_new);
So basically everything might be wrong, but I suppose it is something with fmincon.
EDIT:
The purpose of the alghoritm is to find a minimum of an objective function f(x), satisfying all the constraints g(x,s)<=0 for all s in S, where S is an infinite set (some interval in our case).
What my alghoritm does, at first it takes some finite subset of S and calculates the minimum of f on this set, then I am trying to update S with some s_new. This alghoritm that I am trying to implement is exactly the procedure for creating s_new. Then if it works properly, I will add s_new to my subset and calculate the minimum on the new set, and so on until g(x,s)<=eta, where eta is a small number.
I rewrite the algorithm, read through the comments
clc
clear
lb = 0;
ub = 1;
% Given
l = 3;
M1=linspace(lb,ub,10)';
M2=linspace(lb,ub,100)';
M3=linspace(lb,ub,1000)';
% one boolean value for each Matrix
bool = zeros(1,3);
eta = 10^-8;
% Used as fmincon initial starting guess
pocz = nan;
% Used to store the new finding s that fits all the conditions
s_new = nan;
% Fixed x
x = [0.1,0]';
% fmincon linear constraints
A = [];
b = [];
Aeq = [];
beq = [];
% Main function
g = #(x,s) 5*x(1).^2*sin(pi*sqrt(s))/(1+s.^2) - x(2);
% Optimization concerns s only, don't include x as x is fixed
g_new = #(s) -g(x,s);
% Assuming the maximum is reached at the upper bound, used in(II)(2)
max_s = ub;
maxfun = g(x, max_s);
% Use a cell, for each iteration use a specific matrix M
M = {M1, M2, M3};
for j = 1: length(M)
% used in (II)(1)
check = 0;
step = 1;
% (I) step 1
for i = 1:length(M{j})
% Stopping criteria
if g(x, M{j}(i)) > eta
s_new = M{j}(i);
bool(j) = 1;
break;
else
% Function maximum value for next step (II)
if maxfun < g(x, M{j}(i))
maxfun = g(x, M{j}(i));
% To be used in fmincon as pocz
max_s = M{j}(i);
end
end
% To be used in (II)(1)
if maxfun < -eta
check = 1;
end
end
% End of (I)
% Put (II)(1) here step 2
if ~bool(j) && check
step = step + 1;
% Stopping criteria
if step >= l
disp('S_new not defined');
break;
end
% otherwise go to the next M
end
% (II)(2) step 3
if ~bool(j)
step = step + 1;
if maxfun >= -eta && maxfun <= eta
pocz = max_s;
bool(j) = 1;
end
end
%% EDIT: if bool(j) changed to if ~bool(j)
% (II)(2) Continue
if ~bool(j)
s_maybe = fmincon(g_new,pocz,A,b,Aeq,beq,lb,ub);
% End of (II)(2)
% (II)(2)-1 step 4
step = step + 1;
if g(x, s_maybe) > eta
s_new = s_maybe;
bool(j) = 1;
end
% End of (II)(2)-1
end
% Put (II)(2) here step 5
if ~bool(j)
step = step + 1;
% Stopping criteria
if step >= l
disp('S_new not defined');
break;
end
% otherwise go to the next M
end
end
I am trying to convert my code over to run with parfor, since as it is it takes a long time to run on its own. However I keep getting this error. I have search around on the website and have read people with similar problems, but none of those answers seem to fix my problem. This is my code:
r = 5;
Mu = 12.57e-9;
Nu = 12e6;
I = 1.8;
const = pi*Nu*Mu*r*I;
a = 55;
b = 69;
c = 206;
[m,n,p] = size(Lesion_Visible);
A = zeros(m,n,p);
parpool(2)
syms k
parfor J = 1:m
for I = 1:n
for K = 1:p
if Lesion_Visible(J,I,K) ~= 0
Theta = atand((J-b)/(I-a));
Rho = abs((I-a)/cosd(Theta))*0.05;
Z = abs(c-K)*0.05;
E = vpa(const*int(abs(besselj(0,Rho*k)*exp(-Z*k)*besselj(0,r*k)),0,20),5);
A (J,I,K) = E;
end
end
end
end
I'm trying to calculate the electric field in specific position on an array and matlab give me the error "The variable A in a parfor cannot be classified". I need help. Thanks.
As classification of variables in parfor loop is not permitted, you should try to save the output of each loop in a variable & then save the final output into the desired variable, A in your case!
This should do the job-
parfor J = 1:m
B=zeros(n,p); %create a padding matrix of two dimension
for I = 1:n
C=zeros(p); %create a padding matrix of one dimension
for K = 1:p
if Lesion_Visible(J,I,K) ~= 0
Theta = atand((J-b)./(I-a));
Rho = abs((I-a)./cosd(Theta))*0.05;
Z = abs(c-K).*0.05;
E = vpa(const.*int(abs(besselj(0,Rho.*k).*exp(-Z.*k).*besselj(0,r.*k)),0,20),5);
C(K) = E; %save output of innnermost loop to the padded matrix C
end
end
B(I,:)=C; % save the output to dim1 I of matrix B
end
A(J,:,:)=B; save the output to dim1 J of final matrix A
end
Go through the following for better understanding-
http://www.mathworks.com/help/distcomp/classification-of-variables-in-parfor-loops.html
http://in.mathworks.com/help/distcomp/sliced-variable.html
Here is the code which is trying to solve a coupled PDEs using finite difference method,
clear;
Lmax = 1.0; % Maximum length
Wmax = 1.0; % Maximum wedth
Tmax = 2.; % Maximum time
% Parameters needed to solve the equation
K = 30; % Number of time steps
n = 3; % Number of space steps
m =30; % Number of space steps
M = 2;
N = 1;
Pr = 1;
Re = 1;
Gr = 5;
maxn=20; % The wave-front: intermediate point from which u=0
maxm = 20;
maxk = 20;
dt = Tmax/K;
dx = Lmax/n;
dy = Wmax/m;
%M = a*B1^2*l/(p*U)
b =1/(1+M*dt);
c =dt/(1+M*dt);
d = dt/((1+M*dt)*dy);
%Gr = gB*(T-T1)*l/U^2;
% Initial value of the function u (amplitude of the wave)
for i = 1:n
if i < maxn
u(i,1)=1.;
else
u(i,1)=0.;
end
x(i) =(i-1)*dx;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for j = 1:m
if j < maxm
v(j,1)=1.;
else
v(j,1)=0.;
end
y(j) =(j-1)*dy;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for k = 1:K
if k < maxk
T(k,1)=1.;
else
T(k,1)=0.;
end
z(k) =(k-1)*dt;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Value at the boundary
%for k=0:K
%end
% Implementation of the explicit method
for k=0:K % Time loop
for i=1:n % Space loop
for j=1:m
u(i,j,k+1) = b*u(i,j,k)+c*Gr*T(i,j,k+1)+d*[((u(i,j+1,k)-u(i,j,k))/dy)^(N-1)*((u(i,j+1,k)-u(i,j,k))/dy)]-d*[((u(i,j,k)-u(i,j-1,k))/dy)^(N-1)*((u(i,j,k)-u(i,j-1,k))/dy)]-d*[u(i,j,k)*((u(i,j,k)-u(i-1,j,k))/dx)+v(i,j,k)*((u(i,j+1,k)-u(i,j,k))/dy)];
v(i,j,k+1) = dy*[(u(i-1,j,k+1)-u(i,j,k+1))/dx]+v(i,j-1,k+1);
T(i,j,k+1) = T(i,j,k)+(dt/(Pr*Re))*{(T(i,j+1,k)-2*T(i,j,k)+T(i,j-1,k))/dy^2-Pr*Re{u(i,j,k)*((T(i,j,k)-T(i-1,j,k))/dx)+v(i,j,k)*((T(i,j+1,k)-T(i,j,k))/dy)}};
end
end
end
% Graphical representation of the wave at different selected times
plot(x,u(:,1),'-',x,u(:,10),'-',x,u(:,50),'-',x,u(:,100),'-')
title('graphs')
xlabel('X')
ylabel('Y')
But I am getting this error
Subscript indices must either be real positive integers or logicals.
I am trying to implement this
with boundary conditions
Can someone please help me out!
Thanks
To be quite honest, it looks like you started with something that's way over your head, just typed everything down in one go without thinking much, and now you are surprised that it doesn't work...
In the future, please break down problems like these into waaaay smaller chunks that you can individually plot, check, test, etc. Better yet, try simpler problems first (wave equation, heat equation, ...), gradually working your way up to this.
I say this so harshly, because there were quite a number of fairly basic things wrong with your code:
you've used braces ({}) and brackets ([]) exactly as they are written in the equation. In MATLAB, braces are a constructor for a special container object called a cell array, and brackets are used to construct arrays and matrices. To group things like in the equation, you always have to use parentheses (()).
You had quite a number of parentheses wrong, which became apparent when I re-grouped and broke up those huge unintelligible lines into multiple lines that humans can actually read with understanding
you forgot to take the absolute values in the 3rd and 4th terms of u
you looped over k = 0:K and j = 1:m and then happily index everything with k and j-1. MATLAB is 1-based, meaning, the first element of anything is element 1, and indexing with 0 is an error
you've initialized 3 vectors u, v and T, but then index those in the loop as if they are 3D arrays
Now, I've managed to come up with the following code, which runs OK and at least more or less agrees with the equations shown. But I think it still doesn't make much sense because I get only zeros out (except for the initial values).
But, with this feedback, you should be able to correct any problems left.
Lmax = 1.0; % Maximum length
Wmax = 1.0; % Maximum wedth
Tmax = 2.; % Maximum time
% Parameters needed to solve the equation
K = 30; % Number of time steps
n = 3; % Number of space steps
m = 30; % Number of space steps
M = 2;
N = 1;
Pr = 1;
Re = 1;
Gr = 5;
maxn = 20; % The wave-front: intermediate point from which u=0
maxm = 20;
maxk = 20;
dt = Tmax/K;
dx = Lmax/n;
dy = Wmax/m;
%M = a*B1^2*l/(p*U)
b = 1/(1+M*dt);
c = dt/(1+M*dt);
d = dt/((1+M*dt)*dy);
%Gr = gB*(T-T1)*l/U^2;
% Initial value of the function u (amplitude of the wave)
u = zeros(n,m,K+1);
x = zeros(n,1);
for i = 1:n
if i < maxn
u(i,1)=1.;
else
u(i,1)=0.;
end
x(i) =(i-1)*dx;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
v = zeros(n,m,K+1);
y = zeros(m,1);
for j = 1:m
if j < maxm
v(1,j,1)=1.;
else
v(1,j,1)=0.;
end
y(j) =(j-1)*dy;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
T = zeros(n,m,K+1);
z = zeros(K,1);
for k = 1:K
if k < maxk
T(1,1,k)=1.;
else
T(1,1,k)=0.;
end
z(k) =(k-1)*dt;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Value at the boundary
%for k=0:K
%end
% Implementation of the explicit method
for k = 2:K % Time loop
for i = 2:n % Space loop
for j = 2:m-1
u(i,j,k+1) = b*u(i,j,k) + ...
c*Gr*T(i,j,k+1) + ...
d*(abs(u(i,j+1,k) - u(i,j ,k))/dy)^(N-1)*((u(i,j+1,k) - u(i,j ,k))/dy) - ...
d*(abs(u(i,j ,k) - u(i,j-1,k))/dy)^(N-1)*((u(i,j ,k) - u(i,j-1,k))/dy) - ...
d*(u(i,j,k)*((u(i,j ,k) - u(i-1,j,k))/dx) +...
v(i,j,k)*((u(i,j+1,k) - u(i ,j,k))/dy));
v(i,j,k+1) = dy*(u(i-1,j,k+1)-u(i,j,k+1))/dx + ...
v(i,j-1,k+1);
T(i,j,k+1) = T(i,j,k) + dt/(Pr*Re) * (...
(T(i,j+1,k) - 2*T(i,j,k) + T(i,j-1,k))/dy^2 - Pr*Re*(...
u(i,j,k)*((T(i,j,k) - T(i-1,j,k))/dx) + v(i,j,k)*((T(i,j+1,k) - T(i,j,k))/dy))...
);
end
end
end
% Graphical representation of the wave at different selected times
figure, hold on
plot(x, u(:, 1), '-',...
x, u(:, 10), '-',...
x, u(:, 50), '-',...
x, u(:,100), '-')
title('graphs')
xlabel('X')
ylabel('Y')
I made a matlab code including some symbolic functions
First I run this code, it gives me a result.
But trying to run the same code again, Out of memory message comes up.
Does anybody have an idea to solve this problem?
Below is my code.
clc;
clear;
tic;
rng('shuffle');
p=2; % AR order
yr=normrnd(0,1,1000,1);
T=max(size(yr));
for k=25:35;
intnum=k/10;
fore=100;
int=((max(yr)-min(yr))/intnum);
fin=T-fore;
% Initial setting matrix
y_T1=zeros(fore,1);
y_fore_w=zeros(fore,1); y_diff_w=zeros(fore,1);
y_fore_o=zeros(fore,1);y_diff_o=zeros(fore,1);
y_fore_f=zeros(fore,1);y_diff_f=zeros(fore,1);
y_fore_wl=zeros(fore,1);y_diff_wl=zeros(fore,1);
y_fore_m=zeros(fore,1);y_diff_m=zeros(fore,1);
y_gap=zeros(fore,1);
for e=fin:T-1 ;
y_1=yr(p+1:e);x_1=yr(p:e-1);x_2=yr(p-1:e-2);
A=[y_1 x_1 x_2];
st=1;
ye=yr(st:e);
coordinate = zeros(length(y_1), 3); % Giving new indices to A
y_1_diff=max(y_1)-min(y_1);x_1_diff=max(x_1)-min(x_1);x_2_diff=max(x_2)-min(x_2);
y_1_int=y_1_diff/int;x_1_int=x_1_diff/int;x_2_int=x_2_diff/int;
y_1_int_num=round(y_1_int);x_1_int_num=round(x_1_int);x_2_int_num=round(x_2_int);
for i=1:y_1_int_num;
coordinate(A(:,1) >= (i-1)*int+min(A(:,1)) & A(:,1) < i*int+min(A(:,1)), 1) = i ; % Terrific idea for some conditions in ROW
end
for i=1:x_1_int_num;
coordinate(A(:,2) >= (i-1)*int+min(A(:,2)) & A(:,2) < i*int+min(A(:,2)), 2) = i ; % Terrific idea for some conditions in ROW
end
for i=1:x_2_int_num;
coordinate(A(:,3) >= (i-1)*int+min(A(:,3)) & A(:,3) < i*int+min(A(:,3)), 3) = i; % Terrific idea for some conditions in ROW
end
sz=[y_1_int_num x_1_int_num x_2_int_num];
nucu=max(sz)^(p+1);
y_int_sub_num=zeros(nucu,1); % Number of frequency
yfunc=cell(nucu,1); % Cell of functions
c=1:max(sz);
C=combvec(c,c,c)'; % Generate a reference matrix to coordinate
d=sortrows(C);
syms c b1 b2;
for i=1:nucu;
a=ismember(coordinate, d(i,:), 'rows');
s=sum(a);
y_int_sub_num(i)=s;
B=A(a,:);
func=symfun((B(:,1)-c-b1*B(:,2)-b2*B(:,3)).^2, [c,b1,b2]);
yfunc1=sum(func);
yfunc{i}=yfunc1*y_int_sub_num(i);
clear func; clear yfunc1;
end
yfuncs=symfun(sym('f(c,b1,b2)'),[c,b1,b2]);
for j=1:nucu;
yfuncs=yfuncs+yfunc{j};
end
yfuncs= yfuncs-'f(c,b1,b2)';
y_trans = matlabFunction(yfuncs,'Vars',{[c;b1;b2]});
% WLLS
options = optimset('Algorithm','Interior-point',...
'TolFun',1e-8, 'MaxFunEvals',1000000,'MaxIter',1000000); % Set option
[b_w,fval] = fminsearch(y_trans, [0;0;0], options);
% OLS
c=ones(T-p,1);y_c=zeros(T-p,4);
y_c(:,1)=yr(p+1:T);y_c(:,2)=c;y_c(:,3)=yr(2:end-(p-1));y_c(:,4)=yr(1:end-2);
[b_0,bint_0,e_0,rint,stats] = regress(y_c(:,1), y_c(:,2:4));
% WLS
e_0_w=e_0.^2/sum(e_0.^2); %normalization required for Matlab
[bw,se_bw] = lscov(y_c(:,1), y_c(:,2:4), e_0_w);
% FGLS_iterated
[bf, Sigma] = lscov(y_c(:,1), y_c(:,2:4), e_0_w);
% [bf, Sigma]=fglsi(y_c(:,1), y_c(:,3), y_c(:,4), y_c(:,3));
% MLE
[b_m, b_mm, mu, sig] = regress(y_c(:,1), y_c(:,2:4)); % Since error, OL
% Foracast and Differences
n=e-(fin-1);
y_T1(n)=yr(e+1);
y_fore_w(n)=b_w(1)+b_w(2)*ye(end)+b_w(3)*ye(end-1);y_diff_w(n)=y_T1(n)-y_fore_w(n);
y_fore_o(n)=b_0(1)+b_0(2)*ye(end)+b_0(3)*ye(end-1);y_diff_o(n)=y_T1(n)-y_fore_o(n);
y_fore_wl(n)=bw(1)+bw(2)*ye(end)+bw(3)*ye(end-1);;y_diff_wl(n)=y_T1(n)-y_fore_wl(n);
y_fore_f(n)=bf(1)+bf(2)*ye(end)+bf(3)*ye(end-1);;y_diff_f(n)=y_T1(n)-y_fore_f(n);
y_fore_m(n)=b_m(1)+b_m(2)*ye(end)+b_m(3)*ye(end-1);;y_diff_m(n)=y_T1(n)-y_fore_m(n);
y_gap(n)=abs(y_diff_w(n))-abs(y_diff_o(n));ygap(n)=(y_gap(n)<=0);
end
toc
a=1;filename = [ 'comp', num2str(a), '.mat' ];
save(filename);
if mean(y_diff_w.^2) <=mean(y_diff_o.^2)
[int mean(y_diff_w.^2)]
beep;
end
z1=zeros(y_1_int+1,1);
for i=1:y_1_int+1;
z=(yr>=(i-1)*int+min(yr) & yr<i*int+min(yr));
z1(i)=sum(z);
end
z1
end
sort(yr)
[max(yr) min(yr)]
I'm trying to write a Shidoku ( smaller and easier 4x4 variant of Sudoku) solver code in MATLAB.
I have found some soduko solver (9x9) but i could't revise them to be suitable for my problem. For example:
% Solving Sudoku Using Recursive Backtracking
function X = sudoku(X)
% SUDOKU Solve Sudoku using recursive backtracking.
% sudoku(X), expects a 9-by-9 array X.
% Fill in all “singletons”.
% C is a cell array of candidate vectors for each cell.
% s is the first cell, if any, with one candidate.
% e is the first cell, if any, with no candidates.
[C,s,e] = candidates(X);
while ~isempty(s) && isempty(e)
X(s) = C{s};
[C,s,e] = candidates(X);
end
% Return for impossible puzzles.
if ~isempty(e)
return
end
% Recursive backtracking.
if any(X(:) == 0)
Y = X;
z = find(X(:) == 0,1); % The first unfilled cell.
for r = [C{z}] % Iterate over candidates.
X = Y;
X(z) = r; % Insert a tentative value.
X = sudoku(X); % Recursive call.
if all(X(:) > 0) % Found a solution.
return
end
end
end
% ------------------------------
function [C,s,e] = candidates(X)
C = cell(9,9);
tri = #(k) 3*ceil(k/3-1) + (1:3);
for j = 1:9
for i = 1:9
if X(i,j)==0
z = 1:9;
z(nonzeros(X(i,:))) = 0;
z(nonzeros(X(:,j))) = 0;
z(nonzeros(X(tri(i),tri(j)))) = 0;
C{i,j} = nonzeros(z)';
end
end
end
L = cellfun(#length,C); % Number of candidates.
s = find(X==0 & L==1,1);
e = find(X==0 & L==0,1);
end % candidates
end % sudoku
Any help will be helpful.
Just reduce the problem dimensionality from 3 to 2 (I know now that it is said "9x9" instead of "3x3", but the important dimensional number for the puzzle is N=3):
% SHIDOKU Solve Shidoku using recursive backtracking.
% shidoku(X), expects a 4-by-4 array X.
function X = shidoku(X)
[C,s,e] = candidates(X);
while ~isempty(s) && isempty(e)
X(s) = C{s};
[C,s,e] = candidates(X);
end;
if ~isempty(e)
return
end;
if any(X(:) == 0)
Y = X;
z = find(X(:) == 0,1);
for r = [C{z}]
X = Y;
X(z) = r;
X = shidoku(X);
if all(X(:) > 0)
return;
end;
end;
end;
% ------------------------------
function [C,s,e] = candidates(X)
C = cell(4,4);
bi = #(k) 2*ceil(k/2-1) + (1:2);
for j = 1:4
for i = 1:4
if X(i,j)==0
z = 1:4;
z(nonzeros(X(i,:))) = 0;
z(nonzeros(X(:,j))) = 0;
z(nonzeros(X(bi(i),bi(j)))) = 0;
C{i,j} = transpose(nonzeros(z));
end;
end;
end;
L = cellfun(#length,C); % Number of candidates.
s = find(X==0 & L==1,1);
e = find(X==0 & L==0,1);
end % candidates
end % shidoku