Matrix Dimensions not agreeing

Hi
I am working with the following:
phi = @(ep,r1) exp(-(ep*r1).^2);
ep = 1;
r1=0.1;
S=linspace(0,1);
t=linspace(0,1);
% Randomly Select 10 points from each of S and t.
S_rand = S(sort(randperm(numel(S), 10)));
t_rand = t(sort(randperm(numel(t), 10)));
[S_,t_]=meshgrid(S_rand,t_rand);
X=[S_(:) t_(:)];
D=phi(ep, distm(X,X));
U=bsf(S_,t_,1,1,0.25,0.05);
c=D\U;
I need D to be a 10 x 10 matrix (like U) and not a 100 x 100 matrix as this code is generating. I can't seem to see why this is happening. Any ideas?
Many thanks
Joe

 Accepted Answer

Two ideas:
First, it’s best to always completely vectorise your functions unless you intend matrix operations:
phi = @(ep,r1) exp(-(ep.*r1).^2);
Second, we don’t have ‘distm’. I would break it out into its own variable for troubleshooting purposes to be certain it is not creating your (100x100) matrix:
X=[S_(:) t_(:)];
Q1 = distm(X,X) % See What ‘distm’ Returns
D=phi(ep, distm(X,X));

6 Comments

Hi
Thanks for your response. I have split off the variable as you suggest and vectorised the phi function.
In terms of:
X=[S_(:) t_(:)];
D=phi(ep, distm(X,X));
Is this not taking my new values of S_ and t_ as rows and columns so that the first point is (0th,0th) etc.? Where is the 100*100 coming from?
Sorry if I am not seeing your point!
Thanks again
Joe
My pleasure.
I am hypothesising that your ‘distm’ function (that we still have not seen) is creating the (100x100) matrix. That is the reason you need to insert the ‘Q1’ assignment between those lines:
X=[S_(:) t_(:)];
Q1 = distm(X,X) % See What ‘distm’ Returns
D=phi(ep, distm(X,X));
to see what ‘distm’ is returning.
Hi
Oops! Here it is:
function D=distm(X,Y)
% distm is the distance matrix
% distm(X,Y) is the matrix of the pairwise Euclidean distance
% between the points in the rows of X and Y
[M,s]=size(X);
[N,s]=size(Y);
D=repmat(sum(X.*X,2),1,N)-2*X*Y'+repmat((sum(Y.*Y,2))',M,1);
D=sqrt(D);
Cheers
Joe
Having the ‘distm’ code solved the problem (and absolved it of blame, since it is doing exactly what you asked it to do). The problem is here:
X=[S_(:) t_(:)];
Your ‘X’ is now a (100x2) matrix, and since ‘distm’ creates pairwise distances between the rows of the argument matrices, the size of the output matrix will be (NrowsX x NrowsY), giving you the (100x100) matrix.
Consider using ‘S_rand’ and ‘t_rand’ to create ‘X’ instead, if that fits the logic of your code.
Thanks, that is absolutely fantastic. This is such a great place to learn more about this awesome computer program!
Cheers
Joe
As always, my pleasure! I appreciate your compliment.
It definitely is! MATLAB Answers is where I learned a lot about MATLAB, both by reading other Answers and by helping to solve problems I would never have encountered otherwise.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!