Obtaining different results when using parfor in matlab - matlab

I am trying to parallelize the code below in matlab:
%reduce the size of A if necessary.
A=rand(100,60);
B=int8(rand(size(A,1),size(A,2))>0.5);
N=10;
G=15;
lambda_tol_vector= zeros(G,1);
conto = 1;
for h=-G:0.1:G
lambda_tol_vector(conto)=2^(h);
conto = conto+1;
end
M=4;
tol = 1e-9;
CompletedMat_nopar1={};
tic
for RIPETIZIONE = 1:10
%using normal for loop CompletedMat is saved
for k = 1:size(lambda_tol_vector,1)
%fprintf('Completion using nuclear norm regularization... \n');
%sequential code:
[CompletedMat34,flag] = matrix_completion_nuclear_GG_vec(A.*double(B),double(B),N,lambda_tol_vector(k),tol);
%parallel code thread-based:
if flag==1
CompletedMat_nopar1{RIPETIZIONE,k}=zeros(size(A));
end
CompletedMat_nopar1{RIPETIZIONE,k}=CompletedMat34;
end
end
toc
After having vectorized whereby possible I ended up with the following code:
A = parallel.pool.Constant(A);
lambda_tol_vector=parallel.pool.Constant(lambda_tol_vector);
R=10;
K=size(lambda_tol_vector.Value,1);
CompletedMat_parvec=cell(R,K);
idx=cellfun('isempty', CompletedMat_parvec);
CompletedMat_parvec(idx)={zeros(size(A.Value))};
B=double(B);
tic
parfor n=1:R*K
[~,k]=ind2sub([R,K],n);
%fprintf('Completion using nuclear norm regularization... \n');
[CompletedMat,flag] = matrix_completion_nuclear_GG_vec( ...
A.Value.*B,B, N, lambda_tol_vector.Value(k), tol);
if flag~=0
CompletedMat_parvec{n}=CompletedMat;
end
end
toc
The problem here is that CompletedMat_parvec and CompletedMat_nopar1 provide totally different results while they are expected to give the same result.
How is this possible?
For the sake of completeness I will provide matrix_completion_nuclear_GG_vec below:
%%
% We need a functional environment so that the MAtimesVec subfunction can
% access variables in workspace
function [Anew,objective,flag,iteration] = matrix_completion_nuclear_GG_vec(A,B,N,lambda_tol,tol)
%%
%This code ttries to vectorize and make more efficient the code in
%matrix_completion_nuclear_GG_alt
%% Singular value thresholding for structured (sparse + low rank) matrix
%clear;
%tol=10^-7;
%lambda_tol=0.5;
%%
% Read in sparse matrices downloaded from The University of Florida Sparse
% Matrix Collection
%data = load('mhd4800b.mat');
%A = data.mhd4800b;
%A=A(1:100,1:100);
%A=rand(100,5)*rand(5,100);
%[sA,vA,dA]=svd(A)
%%
% initialization
%B = rand(size(A))<0.3; % remove 10% of the entries
mat=A.*B;
m = size(mat,1);
n = size(mat,2);
L = zeros(m,1);
R = zeros(n,1);
iteration=0;
criterion=0;
flag=0;
Anew=L*R';
objective=zeros();
while (criterion==0 && iteration<N && flag==0)
Aold=Anew;
iteration=iteration+1;
%iteration
%%
% Generation of structured matrix (sparse plus low rank)
%LR = L*R'; % generation of low rank matrix
%Amat = mat + LR; % sparse + low rank
%%
% Find all singular values >= lambda_tol by svt (deflation method). Function
% MAtimesVec is defined at end of this file.
%tic;
%[u,s,v] = svt(#MAtimesVec,'m',m,'n',n,'lambda',lambda_tol);
[u,s,v] = svd(mat+Anew);
%toc;
%display(size(s));
if size(s,1)==0
Anew=NaN*A;
objective=NaN;
flag=1;
return
elseif max(max(s))<=lambda_tol
Anew=NaN*A;
objective=NaN;
flag=1;
return
else
for k=1:min(size(s,1),size(s,2))
if s(k,k)<lambda_tol
s(k,k)=0;
else
s(k,k)=s(k,k)-lambda_tol;
end
end
%size(s,1)
%s=s-lambda_tol*eye(size(s,1));
L=u*s;
R=v;
mat=(A-u*s*v').*B;
Anew=L*R';
objective(iteration)=1/2*(norm(mat,'Fro'))^2+lambda_tol*(sum(diag(s)));
%objective(iteration)
if (norm(Anew-Aold,'Fro')^2/(norm(Aold,'Fro')^2))<tol
criterion=1;
end
%norm(A-Anew,'Fro')
end
end
if flag==1
Anew=[];
objective=[];
end
%%
% Subfunction for exploiting matrix structure of sparse plus low rank
%function MAvec = MAtimesVec(vec, trans)
% if trans
% MAvec = (vec'*mat)' + R*(vec'*L)';
% else
% MAvec = mat*vec + L*(R'*vec);
% end
%end
end

Related

Linear Congruential generator graph

I implemented a simple code for a linear congruential generator
clear all; clc
% Input
m = 59; % module
a = 17; % multiplier
c = 43; % increase
X0 = 27; % seed
n = 100; % sample length
y = [X0 zeros(1,n-1)];
% recursive formula
% X(n+1) = (a*X(n) + c) mod m
for i = 2:n
y(i) = mod(a*y(i-1)+c,m);
end
x = 0:1:n-1;
%for i = 1:n
% plot(x,y);
%end
What I would like to do is a plot where each time the period repeats it draws a vertical line upward as in this graph
I think I have to use the plot function inside a FOR loop and an IF-ELSE to see if the value of the subsequence X(n) is equal to the seed X(0) but I have no idea how to implement it
I think I have to use the plot function inside a FOR loop and an IF-ELSE to see if the value of the subsequence X(n) is equal to the seed X(0) but I have no idea how to implement it

MATLAB's lsim() vs for-loop Simulation // Different results for the same system

I've spent quite some time trying to simulate a simple SISO system using two approaches:
1) Using lsim() in MATLAB
2) By writing down the difference equations myself and iterate over them in a loop.
I was never able to get the same simulation results from both approaches, and I have no idea what I am doing wrong.
I stacked my code in a single m-file so it's easier to follow. Here is the code:
function main()
clear all
clc
simulateUsing_lsim()
simulateUsing_loop()
end
%%%%%% Simulating using lsim %%%%%%%
function simulateUsing_lsim()
% Define the continuous-time closed-loop system
P = getContPlant();
[Kp,Ki,Kd] = get_PIDgains();
C = pid(Kp,Ki,Kd);
clSys_cont = feedback(C*P,1);
% Define the discrete-time closed-loop system
hk = get_sampling_time();
clSys_disc = c2d(clSys_cont,hk);
% Generate the reference signal and the time vector
[r,t] = getReference(hk);
%% Simulate and plot using lsim
figure
lsim(clSys_disc,r,t)
%% Finding and plotting the error
y = lsim(clSys_disc,r);
e = r - y;
figure
p = plot(t,e,'b--');
set(p,'linewidth',2)
legend('error')
xlabel('Time (seconds)')
ylabel('error')
% xlim([-.1 10.1])
end
%%%%%% Simulating using loop iteration (difference equations) %%%%%%%
function simulateUsing_loop()
% Get the cont-time ol-sys
P = getContPlant();
% Get the sampling time
hk = get_sampling_time();
% Get the disc-time ol-sys in SS representation
P_disc = ss(c2d(P,hk));
Ad = P_disc.A;
Bd = P_disc.B;
Cd = P_disc.C;
% Get the PID gains
[Kp,Ki,Kd] = get_PIDgains();
% Generate the reference signal and the time vector
[r,t] = getReference(hk);
%% Perform the system simulation
x = [0 0]'; % Set initial states
e = 0; % Set initial errors
integral_sum = 0; % Set initial integral part value
for i=2:1:length(t)
% Calculate the output signal "y"
y(:,i) = Cd*x;
% Calculate the error "e"
e(:,i) = y(:,i) - r(i);
% Calculate the control signal vector "u"
integral_sum = integral_sum + Ki*hk*e(i);
u(:,i) = Kp*e(i) + integral_sum + (1/hk)*Kd*(e(:,i)-e(:,i-1));
% Saturation. Limit the value of u withing the range [-tol tol]
% tol = 100;
% if abs(u(:,i)) > tol
% u(:,i) = tol * abs(u(:,i))/u(:,i);
% else
% end
% Calculate the state vector "x"
x = Ad*x + Bd*u(:,i); % State transitions to time n
end
%% Subplots
figure
plot(t,y,'b',t,r,'g--')
%% Plotting the error
figure
p = plot(t,e,'r');
set(p,'linewidth',2)
legend('error')
xlabel('Time (seconds)')
ylabel('error')
end
function P = getContPlant()
s = tf('s');
P = 1/(s^2 + 10*s + 20);
end
function [Kp,Ki,Kd] = get_PIDgains()
Kp = 350;
Ki = 300;
Kd = 50;
end
function hk = get_sampling_time()
hk = 0.01;
end
function [r,t] = getReference(hk)
[r,t] = gensig('square',4,10,hk);
end
I got the plant model P and its PID controller from this page (see equation 10), where the system is simulated against a step reference and the result looks pretty much exactly like the lsim() result (just for a single step peak).
However, the result of simulating the system using lsim() is this:
whereas, using the for loop, I got this performance:
I would highly appreciate any help or clarification why I am getting different results.

I need to convert this nested for loop for 3 variables into n variables

This is the program where I use the variable Pesos when Nobj=3. Here I use 3 nested for loops to compute Pesos, but how should I change the code so that it can handle Nobj=n?
Nobj=3;
Card=10;
delta1=1/(Card-1);
alpha1=0:delta1:1;
k=0;
Pesos=zeros(Card^Nobj,Nobj);
for i=1:size(alpha1,2)
for ii=1:size(alpha1,2)
for iii=1:size(alpha1,2)
k=k+1;
Pesos(k,:)=[alpha1(i) alpha1(ii) alpha1(iii)];
if sum(Pesos(k,:))>0
Pesos(k,:)=Pesos(k,:)/sum(Pesos(k,:));
else
Pesos(k,:)=[0 0 1];
end
end
end
end
Vectorize it by using ndgrid:
% Parameters
N = 3;
Card = 10;
% Generate regularly-spaced gridded data of identical
% ranges along N dimensions
alpha1 = linspace(0, 1, Card);
[Pesos{1:N}] = ndgrid(alpha1);
% Expand and concatenate horizontally
Pesos = cellfun(#(x)x(:), Pesos(N:-1:1), 'UniformOutput', false);
Pesos = [Pesos{:}];
% Divide by the row sums
Pesos = bsxfun(#rdivide, Pesos, sum(Pesos,2));
% or
%
% Pesos = Pesos ./ sum(Pesos,2);
%
% if you're on R2016b or later.

Revised Simplex Method - Matlab Script

I've been asked to write down a Matlab program in order to solve LPs using the Revised Simplex Method.
The code I wrote runs without problems with input data although I've realised it doesn't solve the problem properly, as it does not update the inverse of the basis B (the real core idea of the abovementioned method).
The problem is only related to a part of the code, the one in the bottom of the script aiming at:
Computing the new inverse basis B^-1 by performing elementary row operations on [B^-1 u] (pivot row index is l_out). The vector u is transformed into a unit vector with u(l_out) = 1 and u(i) = 0 for other i.
Here's the code I wrote:
%% Implementation of the revised Simplex. Solves a linear
% programming problem of the form
%
% min c'*x
% s.t. Ax = b
% x >= 0
%
% The function input parameters are the following:
% A: The constraint matrix
% b: The rhs vector
% c: The vector of cost coefficients
% C: The indices of the basic variables corresponding to an
% initial basic feasible solution
%
% The function returns:
% x_opt: Decision variable values at the optimal solution
% f_opt: Objective function value at the optimal solution
%
% Usage: [x_opt, f_opt] = S12345X(A,b,c,C)
% NOTE: Replace 12345X with your own student number
% and rename the file accordingly
function [x_opt, f_opt] = SXXXXX(A,b,c,C)
%% Initialization phase
% Initialize the vector of decision variables
x = zeros(length(c),1);
% Create the initial Basis matrix, compute its inverse and
% compute the inital basic feasible solution
B=A(:,C);
invB = inv(B);
x(C) = invB*b;
%% Iteration phase
n_max = 10; % At most n_max iterations
for n = 1:n_max % Main loop
% Compute the vector of reduced costs c_r
c_B = c(C); % Basic variable costs
p = (c_B'*invB)'; % Dual variables
c_r = c' - p'*A; % Vector of reduced costs
% Check if the solution is optimal. If optimal, use
% 'return' to break from the function, e.g.
J = find(c_r < 0); % Find indices with negative reduced costs
if (isempty(J))
f_opt = c'*x;
x_opt = x;
return;
end
% Choose the entering variable
j_in = J(1);
% Compute the vector u (i.e., the reverse of the basic directions)
u = invB*A(:,j_in);
I = find(u > 0);
if (isempty(I))
f_opt = -inf; % Optimal objective function cost = -inf
x_opt = []; % Produce empty vector []
return % Break from the function
end
% Compute the optimal step length theta
theta = min(x(C(I))./u(I));
L = find(x(C)./u == theta); % Find all indices with ratio theta
% Select the exiting variable
l_out = L(1);
% Move to the adjacent solution
x(C) = x(C) - theta*u;
% Value of the entering variable is theta
x(j_in) = theta;
% Update the set of basic indices C
C(l_out) = j_in;
% Compute the new inverse basis B^-1 by performing elementary row
% operations on [B^-1 u] (pivot row index is l_out). The vector u is trans-
% formed into a unit vector with u(l_out) = 1 and u(i) = 0 for
% other i.
M=horzcat(invB,u);
[f g]=size(M);
R(l_out,:)=M(l_out,:)/M(l_out,j_in); % Copy row l_out, normalizing M(l_out,j_in) to 1
u(l_out)=1;
for k = 1:f % For all matrix rows
if (k ~= l_out) % Other then l_out
u(k)=0;
R(k,:)=M(k,:)-M(k,j_in)*R(l_out,:); % Set them equal to the original matrix Minus a multiple of normalized row l_out, making R(k,j_in)=0
end
end
invM=horzcat(u,invB);
% Check if too many iterations are performed (increase n_max to
% allow more iterations)
if(n == n_max)
fprintf('Max number of iterations performed!\n\n');
return
end
end % End for (the main iteration loop)
end % End function
%% Example 3.5 from the book (A small test problem)
% Data in standard form:
% A = [1 2 2 1 0 0;
% 2 1 2 0 1 0;
% 2 2 1 0 0 1];
% b = [20 20 20]';
% c = [-10 -12 -12 0 0 0]';
% C = [4 5 6]; % Indices of the basic variables of
% % the initial basic feasible solution
%
% The optimal solution
% x_opt = [4 4 4 0 0 0]' % Optimal decision variable values
% f_opt = -136 % Optimal objective function cost
Ok, after a lot of hrs spent on the intensive use of printmat and disp to understand what was happening inside the code from a mathematical point of view I realized it was a problem with the index j_in and normalization in case of dividing by zero therefore I managed to solve the issue as follows.
Now it runs perfectly. Cheers.
%% Implementation of the revised Simplex. Solves a linear
% programming problem of the form
%
% min c'*x
% s.t. Ax = b
% x >= 0
%
% The function input parameters are the following:
% A: The constraint matrix
% b: The rhs vector
% c: The vector of cost coefficients
% C: The indices of the basic variables corresponding to an
% initial basic feasible solution
%
% The function returns:
% x_opt: Decision variable values at the optimal solution
% f_opt: Objective function value at the optimal solution
%
% Usage: [x_opt, f_opt] = S12345X(A,b,c,C)
% NOTE: Replace 12345X with your own student number
% and rename the file accordingly
function [x_opt, f_opt] = S472366(A,b,c,C)
%% Initialization phase
% Initialize the vector of decision variables
x = zeros(length(c),1);
% Create the initial Basis matrix, compute its inverse and
% compute the inital basic feasible solution
B=A(:,C);
invB = inv(B);
x(C) = invB*b;
%% Iteration phase
n_max = 10; % At most n_max iterations
for n = 1:n_max % Main loop
% Compute the vector of reduced costs c_r
c_B = c(C); % Basic variable costs
p = (c_B'*invB)'; % Dual variables
c_r = c' - p'*A; % Vector of reduced costs
% Check if the solution is optimal. If optimal, use
% 'return' to break from the function, e.g.
J = find(c_r < 0); % Find indices with negative reduced costs
if (isempty(J))
f_opt = c'*x;
x_opt = x;
return;
end
% Choose the entering variable
j_in = J(1);
% Compute the vector u (i.e., the reverse of the basic directions)
u = invB*A(:,j_in);
I = find(u > 0);
if (isempty(I))
f_opt = -inf; % Optimal objective function cost = -inf
x_opt = []; % Produce empty vector []
return % Break from the function
end
% Compute the optimal step length theta
theta = min(x(C(I))./u(I));
L = find(x(C)./u == theta); % Find all indices with ratio theta
% Select the exiting variable
l_out = L(1);
% Move to the adjacent solution
x(C) = x(C) - theta*u;
% Value of the entering variable is theta
x(j_in) = theta;
% Update the set of basic indices C
C(l_out) = j_in;
% Compute the new inverse basis B^-1 by performing elementary row
% operations on [B^-1 u] (pivot row index is l_out). The vector u is trans-
% formed into a unit vector with u(l_out) = 1 and u(i) = 0 for
% other i.
M=horzcat(u, invB);
[f g]=size(M);
if (theta~=0)
M(l_out,:)=M(l_out,:)/M(l_out,1); % Copy row l_out, normalizing M(l_out,1) to 1
end
for k = 1:f % For all matrix rows
if (k ~= l_out) % Other then l_out
M(k,:)=M(k,:)-M(k,1)*M(l_out,:); % Set them equal to the original matrix Minus a multiple of normalized row l_out, making R(k,j_in)=0
end
end
invB=M(1:3,2:end);
% Check if too many iterations are performed (increase n_max to
% allow more iterations)
if(n == n_max)
fprintf('Max number of iterations performed!\n\n');
return
end
end % End for (the main iteration loop)
end % End function
%% Example 3.5 from the book (A small test problem)
% Data in standard form:
% A = [1 2 2 1 0 0;
% 2 1 2 0 1 0;
% 2 2 1 0 0 1];
% b = [20 20 20]';
% c = [-10 -12 -12 0 0 0]';
% C = [4 5 6]; % Indices of the basic variables of
% % the initial basic feasible solution
%
% The optimal solution
% x_opt = [4 4 4 0 0 0]' % Optimal decision variable values
% f_opt = -136 % Optimal objective function cost

Undefined function 'qquadrature' for input arguments of type 'double'

I'm a new user of Matlab, can you please help:
I have the following code in an .M file:
`% free vibration of non-prismatic Euler beams with or without axial load
%using differential quadrature method
clc;
ne=50;
n=ne+1;
nn=2*n;
no=4;
m=zeros(n,1);
x=zeros(n,1);
xi=zeros(n,1);
c=zeros(n,n,no);
d=zeros(n+4,n+4);
e=zeros(n+4,n+4);
z=zeros(n+4,1);
f=zeros(n+4,1);
alp=zeros(n,n);
bet=zeros(n,n);
zz=zeros(n,1);
ki=zeros(n,n);
eta=zeros(n,n);
const=1.0;
l=12;
ymod=200e09;
rho=7800;
format long;
for i=1:n
xi(i)=0.5*(1-cos((i-1)*pi/ne));
%mi(i)=0.000038*(1-xi(i)^2/2);
ar(i)=1/rho;
mi(i)=0.000038;
ki(i,i)=ymod*mi(i);
end
c=qquadrature(xi,n,no);
%c = harquadrature(xi,n,no)
for i = 1:n
alp(i,i) = 0;
bet(i,i) = 0;
for j = 1:n
alp(i,i) = alp(i,i)+c(i,j,1)*ki(j,j)/l;
bet(i,i) = bet(i,i)+c(i,j,2)*ki(j,j)/l^2;
end
end
d=zeros(n+4,n+4);
% free vibration of the beam
% axial load on the beam t=+ if it is compressive t=- if it is tensile
% weight of the beam / unit length
t=520895.0;
d(1:n,1:n)=2.0*alp*c(:,:,3)/l^3+bet*c(:,:,2)/l^2+ki*c(:,:,4)/l^4+eta+t*c(:,:,2)/l^2;
% boundary conditions
% clamped - free
% d(n+1,1)=1.0;
% d(n+2:n+2,1:n)=alp(n,n)*c(n,1:n,2)/l^2+ki(n,n)*c(n,1:n,3)/l^3+t*c(n,1:n,1)/l;
% d(n+3:n+3,1:n)=c(1,1:n,1)/l;
% d(n+4:n+4,1:n)=ki(n,n)*c(n,1:n,2)/l^2;
% d(1,n+1)=1.0;
% for i=1:n
% d(i,n+2)=d(n+2,i);
% d(i,n+3)=d(n+3,i);
% d(i,n+4)=d(n+4,i);
% end
% pinned - pinned
d(n+1,1)=1.0;
d(n+2:n+2,1:n)=ki(n,n)*c(n,1:n,2)/l^2;
d(n+3:n+3,1:n)=ki(1,1)*c(1,1:n,2)/l^2;
d(n+4,n)=1.0;
d(n,n+4)=1.0;
d(1,n+1)=1.0;
d(n+4,n)=1.0;
for i = 1:n
d(i,n+2)=d(n+2,i);
d(i,n+3)=d(n+3,i);
end
e=zeros(n+4,n+4);
for i=1:n
e(i,i)=rho*ar(i);
end
z=d\e;
[ev,euv]=eig(z);
for i=1:n
zz(z)=ev(i,5);
end
omega=sqrt(1/euv(5,5));
sprintf(' natural frequency\n')
omega;
figure(1);
plot(xi,zz)
xlabel(' x/L ')
ylabel(' z')
title (' fundamental mode shape ')`
I have stored this file (Untitled.M) in the normal Matlab path, and therefore I'm assuming that Matlab will read the function when it's starting and that this function therefore should be available to use.
Then I am trying to run this single M-files.
But "Undefined function 'qquadrature' for input arguments of type 'double'" message appears..
Can somebody show me where's the problem and how ti fix it?
Thankyou..