Plotting distance of each point in a grid from a mean
5 views (last 30 days)
Show older comments
I'm trying to shade in a grid using p-color to represent the mahalanobis distance from a certain 2d mean point. However I can't seem to get it right. I think my problem is in iterating over every point in the 179 by 179 grid, I'm not constructing the loop right to get the iteration right. I am new to matlab and really struggling with the syntax and "matrix algebra" approach to data analysis.
here is my code:
M = 179
N=179
x = linspace(-0.5, 1.0, M);
y = linspace(-0.5, 1..0, N);
D = zeros(M,N);
for i = 1:M;
j = 1:N
D(i, j) = sqrt(([x(i),y(j)] -mean(Xtr(I, :)))'.*cov(Xtr).*([x(i),y(j)] -mean(Xtr(I,:))));
end
end
h = pcolor(x, y, D)
set(h, 'EdgeColor', 'none')
axis equal
axis tight
colorbar
scatter(Xtr)
hold on
I = find(ttr == 0)
scatter(Xtr(I, 1), Xtr(I,2), 10, 'bx')
hold on
II = find(ttr == 1)
scatter(Xtr(II,1), Xtr(II,2), 10, 'ro')
hold on
4 Comments
dpb
on 12 Sep 2018
Well, in that case, that leads to the Q? of what is ttr?
What are dimensions for Xtr and ttr?
Answers (3)
Image Analyst
on 12 Sep 2018
Definitions I see have the inverse of the covariance matrix in there, not the covariance matrix itself.
0 Comments
dpb
on 13 Sep 2018
Edited: dpb
on 13 Sep 2018
M=size(Xtr,1);
N=size(ttr,1);
mnXtr=mean(Xtr(Xtr~=0),:);
[X Y]=meshgrid(linspace(-0.5, 1.0, M),linspace(-0.5, 1..0, N));
D=sqrt(mahal([X Y],Xtr));
2 Comments
dpb
on 13 Sep 2018
I also overlooked writing the trailing ":" for the second dimension in computing the mean vector...fixed that in the Answer.
And, yeah, meshgrid builds a 2D array for each...to use w/ mahal, have to build the combination vector to make the list of points pairwise...
D=sqrt(mahal([X(:) Y(:)],Xtr));
but then it says
"The number of rows of X must exceed number of columns."
I'll admit I don't understand the function at all; don't see why that has any bearing on anything.
Seems as though it should just compute the distance to the given feature vector it's given and be satisfied with that.
I surrender... :)
As IA suggests, perhaps pdist2?
Image Analyst
on 13 Sep 2018
Why not use pdist2() if you have the Statistics and Machine Learning Toolbox?
0 Comments
See Also
Categories
Find more on Discrete Math in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!