"Not enough input arguments" when publishing MATLAB commands - matlab

I've written the following code:
function [a1,b1,a0,b0] = Conformal_2D(x_input,y_input,X_output,Y_output)
%%
% Calculates parameters $a,b,a_0,b_0$ in the following equation using least
% squares
%%
%
% $$X=a_1x+b_1y+a_0$$
%
% $$X=-b_1x+a_1y+b_0$$
%%
% *Arguments:*
%
% x_input is a $n\times 1$ matrix containing x coordinate of control points
% in the input space
%
% y_input is a $n\times 1$ matrix containing y coordinate of control points
% in the input space
%
% x_output is a $n\times 1$ matrix containing x coordinate of control points
% in the output space
%
% y_output is a $n\times 1$ matrix containing y coordinate of control points
% in the output space
%%
NumberOfPoints = size(x_input,1);
A = zeros(2*NumberOfPoints,1); % Coefficient matrix in AX = L
L = zeros(2*NumberOfPoints,1); % Right-hand matrix in AX = L
for i = 1:NumberOfPoints
A(2*i-1,1:4) = [x_input(i,1) y_input(i,1) 1 0];
end
end
When I press 'Publish' button, I get:
What's the problem with that line?

Not sure if this is the best workaround, but I managed to publish the function with the following script. Of course, you will use your own entries for x_input, y_inpyt, etc. Make sure that you save the following script in a file not named Conformal_2D.m.
Conformal_2D([3;2;1],[5;6;7],[11;12;13],[14;15;16]);
function [a1,b1,a0,b0] = Conformal_2D(x_input,y_input,X_output,Y_output)
%%
% Calculates parameters $a,b,a_0,b_0$ in the following equation using least
% squares
%%
%
% $$X=a_1x+b_1y+a_0$$
%
% $$X=-b_1x+a_1y+b_0$$
%%
% *Arguments:*
%
% x_input is a $n\times 1$ matrix containing x coordinate of control points
% in the input space
%
% y_input is a $n\times 1$ matrix containing y coordinate of control points
% in the input space
%
% x_output is a $n\times 1$ matrix containing x coordinate of control points
% in the output space
%
% y_output is a $n\times 1$ matrix containing y coordinate of control points
% in the output space
%%
NumberOfPoints = size(x_input,1);
A = zeros(2*NumberOfPoints,1); % Coefficient matrix in AX = L
L = zeros(2*NumberOfPoints,1); % Right-hand matrix in AX = L
for i = 1:NumberOfPoints
A(2*i-1,1:4) = [x_input(i,1) y_input(i,1) 1 0];
end
end

When publishing, MATLAB runs the code by default. Of course, your function has input arguments that will not be set in this case (see this other question).
There are a few ways around this. Juanchito's answer illustrates one: don't publish a function, publish a script.
Alternatively, publish the function without executing it:
publish('Conformal_2D.m','evalCode',false)
Or, give MATLAB the right declarations to evaluate before executing the function's content:
publish('Conformal_2D.m','codeToEvaluate','x_input=1; y_input=2; X_output=3; Y_output=4')
(do adjust those values, of course).

Related

bin2mat running slow need a faster solution

I am using bin2mat function from matlab file exchange, for some reason it runs very slow. Is it possible to make it run faster or is there an alternative? I am trying: zC = bin2mat(s.X,s.Y,s.Z,xC,yC); I am not sure where it gets bogged down. I need to do this on point cloud data to calculate volume and such.
Here is the code:
function ZG = bin2mat(x,y,z,XI,YI,varargin)
% BIN2MAT - create a matrix from scattered data without interpolation
%
% ZG = BIN2MAT(X,Y,Z,XI,YI) - creates a grid from the data
% in the (usually) nonuniformily-spaced vectors (x,y,z)
% using grid-cell averaging (no interpolation). The grid
% dimensions are specified by the uniformily spaced vectors
% XI and YI (as produced by meshgrid).
%
% ZG = BIN2MAT(...,#FUN) - evaluates the function FUN for each
% cell in the specified grid (rather than using the default
% function, mean). If the function FUN returns non-scalar output,
% the output ZG will be a cell array.
%
% ZG = BIN2MAT(...,#FUN,ARG1,ARG2,...) provides aditional
% arguments which are passed to the function FUN.
%
% EXAMPLE
%
% %generate some scattered data
% [x,y,z]=peaks(150);
% ind=(rand(size(x))>0.9);
% xs=x(ind); ys=y(ind); zs=z(ind);
%
% %create a grid, use lower resolution if
% %no gaps are desired
% xi=min(xs):0.25:max(xs);
% yi=min(ys):0.25:max(ys);
% [XI,YI]=meshgrid(xi,yi);
%
% %calculate the mean and standard deviation
% %for each grid-cell using bin2mat
% Zm=bin2mat(xs,ys,zs,XI,YI); %mean
% Zs=bin2mat(xs,ys,zs,XI,YI,#std); %std
%
% %plot the results
% figure
% subplot(1,3,1);
% scatter(xs,ys,10,zs,'filled')
% axis image
% title('Scatter Data')
%
% subplot(1,3,2);
% pcolor(XI,YI,Zm)
% shading flat
% axis image
% title('Grid-cell Average')
%
% subplot(1,3,3);
% pcolor(XI,YI,Zs)
% shading flat
% axis image
% title('Grid-cell Std. Dev.')
%
% SEE also RESHAPE ACCUMARRAY FEVAL
% A. Stevens 3/10/2009
% astevens#usgs.gov
%check inputs
error(nargchk(5,inf,nargin,'struct'));
%make sure the vectors are column vectors
x = x(:);
y = y(:);
z = z(:);
if all(any(diff(cellfun(#length,{x,y,z}))));
error('Inputs x, y, and z must be the same size');
end
%process optional input
fun=#mean;
test=1;
if ~isempty(varargin)
fun=varargin{1};
if ~isa(fun,'function_handle');
fun=str2func(fun);
end
%test the function for non-scalar output
test = feval(fun,rand(5,1),varargin{2:end});
end
%grid nodes
xi=XI(1,:);
yi=YI(:,1);
[m,n]=size(XI);
%limit values to those within the specified grid
xmin=min(xi);
xmax=max(xi);
ymin=min(yi);
ymax=max(yi);
gind =(x>=xmin & x<=xmax & ...
y>=ymin & y<=ymax);
%find the indices for each x and y in the grid
[junk,xind] = histc(x(gind),xi);
[junk,yind] = histc(y(gind),yi);
%break the data into a cell for each grid node
blc_ind=accumarray([yind xind],z(gind),[m n],#(x){x},{NaN});
%evaluate the data in each grid using FUN
if numel(test)>1
ZG=cellfun(#(x)(feval(fun,x,varargin{2:end})),blc_ind,'uni',0);
else
ZG=cellfun(#(x)(feval(fun,x,varargin{2:end})),blc_ind);
end
It is slower on these two steps for one run it took:
ZG=cellfun(#(x)(feval(fun,x,varargin{2:end})),blc_ind); took 33 secs
blc_ind=accumarray([yind xind],z(gind),[m n],#(x){x},{NaN}); took 10 secs
You can change blc_ind = ... to
ZG=accumarray([yind xind],z(gind),[m n],#mean,NaN);
and delete other codes form here so the is no need to if numel(test)>1....

frequency spectrum of sinc function in matlab shows me nothing

since i don't have sinc function in my MATLAB,
I implemented that function as shown below
%% time specificactions:
Fs=10000; dt=1/Fs; t=(-0.1:dt:0.1-dt)'; N=size(t,1);
%message signal
mt=(sin(pi*100*t))./(pi*100*t);
%% frequency specifications
dF=Fs/N;
f=-Fs/2:dF:Fs/2-dF;
M=fftshift(fft(mt));
plot(f,abs(M)/N);
but the figure shows me nothing but blank, so i looked up the variable table and it is filled with NaN.
One thing I don't understand that is that the exactly same procedure worked pretty well when the function i want to fourier transform was just cosine function.
You have a wrongly defined sinc function, as when t=0 it outputs NaN.
you can check that doing any(isnan(mt)) in your code.
To define properly the function do
mt(find(t==0))=1;
That will make your code output
You may want to reconsider the parameters in order to see better the square wave.
the source code of sinc function in Matlab:
function y=sinc(x)
%SINC Sin(pi*x)/(pi*x) function.
% SINC(X) returns a matrix whose elements are the sinc of the elements
% of X, i.e.
% y = sin(pi*x)/(pi*x) if x ~= 0
% = 1 if x == 0
% where x is an element of the input matrix and y is the resultant
% output element.
%
% % Example of a sinc function for a linearly spaced vector:
% t = linspace(-5,5);
% y = sinc(t);
% plot(t,y);
% xlabel('Time (sec)');ylabel('Amplitude'); title('Sinc Function')
%
% See also SQUARE, SIN, COS, CHIRP, DIRIC, GAUSPULS, PULSTRAN, RECTPULS,
% and TRIPULS.
% Author(s): T. Krauss, 1-14-93
% Copyright 1988-2004 The MathWorks, Inc.
% $Revision: 1.7.4.1 $ $Date: 2004/08/10 02:11:27 $
i=find(x==0);
x(i)= 1; % From LS: don't need this is /0 warning is off
y = sin(pi*x)./(pi*x);
y(i) = 1;

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

plot 3D line, matlab

My question is pretty standard but can't find a solution of that.
I have points=[x,y,z] and want to plot best fit line.
I am using function given below (and Thanx Smith)
% LS3DLINE.M Least-squares line in 3 dimensions.
%
% Version 1.0
% Last amended I M Smith 27 May 2002.
% Created I M Smith 08 Mar 2002
% ---------------------------------------------------------------------
% Input
% X Array [x y z] where x = vector of x-coordinates,
% y = vector of y-coordinates and z = vector of
% z-coordinates.
% Dimension: m x 3.
%
% Output
% x0 Centroid of the data = point on the best-fit line.
% Dimension: 3 x 1.
%
% a Direction cosines of the best-fit line.
% Dimension: 3 x 1.
%
% <Optional...
% d Residuals.
% Dimension: m x 1.
%
% normd Norm of residual errors.
% Dimension: 1 x 1.
% ...>
%
% [x0, a <, d, normd >] = ls3dline(X)
I have a.
So equation may be
points*a+dist=0
where dist is min. distance from origon.
Now my question is how to plot best filt line in 3D.
It helps to actually read the content of the function, which uses Singular Value Decomposition.
% calculate centroid
x0 = mean(X)';
% form matrix A of translated points
A = [(X(:, 1) - x0(1)) (X(:, 2) - x0(2)) (X(:, 3) - x0(3))];
% calculate the SVD of A
[U, S, V] = svd(A, 0);
% find the largest singular value in S and extract from V the
% corresponding right singular vector
[s, i] = max(diag(S));
a = V(:, i);
The best orthogonal fitting line is
P = x0 + a.*t
as the parameter t varies. This is the direction of maximum variation which means that variation in the orthogonal direction is minimum. The sum of the squares of the points' orthogonal distances to this line is minimized.
This is distinct from linear regression which minimizes the y variation from the line of regression. That regression assumes that all errors are in the y coordinates, whereas orthogonal fitting assumes the errors in both the x and y coordinates are of equal expected magnitudes.
[Credit: Roger Stafford , http://www.mathworks.com/matlabcentral/newsreader/view_thread/294030]
Then you only need to create some t and plot it:
for t=0:100,
P(t,:) = x0 + a.*t;
end
scatter3(P(:,1),P(:,2),P(:,3));
You may want to use plot3() instead, in which case you need only a pair of points. Since a line is infinite by definition, it is up to you to determine where it should begin and end (depends on application).

Plotting a graph from its adjacency matrix

I am looking for a command in MATLAB which could help me to plot a graph given the adjacency matrix. Can anyone help me? Further I need some graph tools to compute shortest distances between points on a graph, diameter of a set, distance between sets etc. Thanks
Check this Matlab Function by Haruna Matsushita
function [Xout,Yout,Zout]=gplot3(A,xy,lc)
% gplot‚Ì3ŽŸŒ³•\Ž¦
%
% 2005/04/11 Haruna MATSUSHITA
%GPLOT Plot graph, as in "graph theory".
% GPLOT(A,xy) plots the graph specified by A and xy. A graph, G, is
% a set of nodes numbered from 1 to n, and a set of connections, or
% edges, between them.
%
% In order to plot G, two matrices are needed. The adjacency matrix,
% A, has a(i,j) nonzero if and only if node i is connected to node
% j. The coordinates array, xy, is an n-by-2 matrix with the
% position for node i in the i-th row, xy(i,:) = [x(i) y(i)].
%
% GPLOT(A,xy,LineSpec) uses line type and color specified in the
% string LineSpec. See PLOT for possibilities.
%
% [X,Y] = GPLOT(A,xy) returns the NaN-punctuated vectors
% X and Y without actually generating a plot. These vectors
% can be used to generate the plot at a later time if desired.
%
% See also SPY, TREEPLOT.
% John Gilbert, 1991.
% Modified 1-21-91, LS; 2-28-92, 6-16-92 CBM.
% Copyright 1984-2002 The MathWorks, Inc.
% $Revision: 5.12 $ $Date: 2002/04/09 00:26:12 $
[i,j] = find(A);
[ignore, p] = sort(max(i,j));
i = i(p);
j = j(p);
% Create a long, NaN-separated list of line segments,
% rather than individual segments.
X = [ xy(i,1) xy(j,1) repmat(NaN,size(i))]';
Y = [ xy(i,2) xy(j,2) repmat(NaN,size(i))]';
Z = [ xy(i,3) xy(j,3) repmat(NaN,size(i))]';
X = X(:);
Y = Y(:);
Z = Z(:);
if nargout==0,
if nargin<3,
plot3(X, Y, Z)
else
plot3(X, Y, Z,lc,'MarkerFaceColor','none','MarkerEdgeColor','b','MarkerSize',5);
end
else
Xout = X;
Yout = Y;
Zout = Z;
end
Given the adjacency matrix M, plotting the corresponding directed graph in Matlab will be as easy as:
G = digraph(M);
plot(G)