I am trying to find the sum of certain coordinates in a matrix.
I have a N x M matrix. I have a vector which contains 2xM values. Every pair of values in the vector is a coordinate in the matrix. Hence their are M number of coordinates. I want to find the sum of all of the coordinates without using a for loop.
Is there a matrix operation I can use to get this?
Thanks
As I understand it the vector contains the (row,column) coordinates to the matrix elements. You can just transform them into matrix element number indices. This example shows how to do it. I'm assuming that your coordinate vector looks like this:
[n-coordinate1 m-coordinate1 n-coordinate2 m-coordinate2 ...]
n = 5; % number of rows
m = 5; % number of columns
matrix = round(10*rand(n,m)); % An n by m example matrix
% A vector with 2*m elements. Element 1 is the n coordinate,
% Element 2 the m coordinate, and so on. Indexes into the matrix:
vector = ceil(rand(1,2*m)*5);
% turn the (n,m) coordinates into the element number index:
matrixIndices = vector(1:2:end) + (vector(2:2:end)-1)*n);
sumOfMatrixElements = sum(matrix(matrixIndices)); % sums the values of the indexed matrix elements
If you want to find the centroid of your 2xM array coords, then you can simply write
centroid = mean(coords,2)
If you want to find the weighted centroid, where each coordinate pair is weighted by the corresponding entry in the MxN array A, you can use sub2ind like this:
idx = sub2ind(size(A),coords(1,:)',coords(2,:)');
weights = A(idx);
weightedCentroid = sum( bsxfun( #times, coords', weights), 1 ) / sum(weights);
If all you want is the sum of all the entries to which the coordinates point, you can do the above and simply sum the weights:
idx = sub2ind(size(A),coords(1,:)',coords(2,:)');
weights = A(idx);
sumOfValues = sum(weights);
Related
I have a data set (called A) which contains positive integer numbers.
I want to find numbers in x and y axis of the histogram of A in two different vectors. I want a vector of unique values and a vector with the count for each values.
To obtain a vector x of unique values and a vector y of their occurrence counts:
x = unique(A(:)).';
y = sum(bsxfun(#eq,A(:),x),1);
Or, alternatively,
x = unique(A(:)).';
y = histcounts(A, [x inf]);
I have 100 coordinates in a variable x in MATLAB . How can I make sure that distance between all combinations of two points is greater than 1?
You can do this in just one simple line, with the functions all and pdist:
if all(pdist(x)>1)
...
end
Best,
First you'll need to generate a matrix that gives you all possible pairs of coordinates. This post can serve as inspiration:
Generate a matrix containing all combinations of elements taken from n vectors
I'm going to assume that your coordinates are stored such that the columns denote the dimensionality and the rows denote how many points you have. As such, for 2D, you would have a 100 x 2 matrix, and in 3D you would have a 100 x 3 matrix and so on.
Once you generate all possible combinations, you simply compute the distance... which I will assume it to be Euclidean here... of all points and ensure that all of them are greater than 1.
As such:
%// Taken from the linked post
vectors = { 1:100, 1:100 }; %// input data: cell array of vectors
n = numel(vectors); %// number of vectors
combs = cell(1,n); %// pre-define to generate comma-separated list
[combs{end:-1:1}] = ndgrid(vectors{end:-1:1}); %// the reverse order in these two
%// comma-separated lists is needed to produce the rows of the result matrix in
%// lexicographical order
combs = cat(n+1, combs{:}); %// concat the n n-dim arrays along dimension n+1
combs = reshape(combs,[],n); %// reshape to obtain desired matrix
%// Index into your coordinates array
source_points = x(combs(:,1), :);
end_points = x(combs(:,2), :);
%// Checks to see if all distances are greater than 1
is_separated = all(sqrt(sum((source_points - end_points).^2, 2)) > 1);
is_separated will contain either 1 if all points are separated by a distance of 1 or greater and 0 otherwise. If we dissect the last line of code, it's a three step procedure:
sum((source_points - end_points).^2, 2) computes the pairwise differences between each component for each pair of points, squares the differences and then sums all of the values together.
sqrt(...(1)...) computes the square root which gives us the Euclidean distance.
all(...(2)... > 1) then checks to see if all of the distances computed in Step #2 were greater than 1 and our result thus follows.
I need to generate all square matrices of order n with given properties.
Matrices are symmetric.
Entries are 0 and 1.
Diagonal elements are zeros.
I am using Matlab2012b. Can you help me with the code?
I was trying to write it down. It needs a long sequences of for loops. Any simpler technique?
Try this:
N = 4; %// matrix size
M = (N^2-N)/2; %// number of values to fill in each matrix
P = 2^M; %// number of matrices
x = dec2bin(0:P-1)-'0'; %// each row contains the values of a matrix, "packed" in a vector
result = NaN(N,N,P); %// preallocate
for k = 1:P
result(:,:,k) = squareform(x(k,:)); %// unpack values
end
The matrices are result(:,:,1), result(:,:,2) etc.
I have a matrix D(i,j,k) and I want to find i,j,k so as to minimize x:
x = D(i,j,k)
For example:
D = rand(10,10,10);
min(min(min(D))) = 0.5123; %The smallest element in D
What I want to know is the index of D that gives 0.5123
How can I do this?
Thanks,
Elliot
Try min with the colon operator, then ind2sub:
[xmin,ind] = min(D(:));
[ii,jj,kk] = ind2sub(size(D),ind)
The answer by #chappjc is perfect for the 3D case.
For the n-dimensional case, use as the output of ind2sub a comma-separated list obtained from a cell array of size n:
indices = cell(1,ndims(D)); %// define number of indices (size of cell array)
[minVal linInd] = min(D(:)); %// linear index of minimizer
[indices{:}] = ind2sub(size(D),linInd); %// return indices in cell array
indices = cell2mat(indices); %// convert to nx1 vector containing the indices
You can use the find function.
D = rand(10,10,10);
[I, J]=find(D == min(min(min(D))));
Note that for matrices of more than 2 dimensions:
If X is an N-dimensional array where N > 2, then J is a linear index over the N-1 trailing
dimensions of X
see: http://www.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html
Hope it helps
I have a problem like that;
points (size = 65,2) is a variable that has pixel coordinates of an image. In the first column, there are x coordinates, and in the second y coordinates and I want to take the magnitude values of a matrix (size = 256,256,6) from those pixel coordinates of only one channel eg. 3 (three).
I couldn't succeed that.
intensities = images(points(:,2), points(:,1), 3);
makes a matrix 65x65.
Thanks
Jimenez
You can convert your x,y indices to linear indices to get values you want from your image:
% some sample data
list = round(256*rand(65,2));
im = rand(256,256);
% calculate linear indices
ind = sub2ind([256,256],list(:,1),list(:,2));
intensities = im(ind);
This results in an intensities matrix that is 65x1 where each element corresponds to the x,y pair from your list.