Index position of randsample in Matlab - matlab

I'm using the randsample function of Matlab to sample a data point in the following way:
points = randi(100,1,10);
weighting_vector = rand(1,10);
normalized_weighting_vector = weighting_vector ./ sum(weighting_vector);
point = randsample(points,1,'true',normalized_weighting_vector);
How can I get the index of the selected point?
For example if points = [1,2,2,3,4,4,4,8,9,3] and point = 4, I would like to know the index position of the chosen value, which can either be 5, 6 or 7.

Rather than using randsample on your data, randomly sample the indices and then convert these indices to their corresponding values in points.
points = [1,2,2,3,4,4,4,8,9,3];
% Randomly choose N indices from the possible index values for points
index = randsample(1:numel(points), 1, true);
% Get the point corresponding to these indices
point = points(index)

Related

How to plot a vector in matlab with another vector as a parameter?

I am trying to optimize the speed of a function I am writing, and trying to use vectors as much as I can. I am new to Matlab and vectorization is sometimes understandable to me, but I would like some additional help. Here is my current code:
For note, the oracle() function represents a randomly shaped object, and if you input a 1x2 matrix, it will return whether or not the matrx (or in our case, x- y-coordinates) is inside the random object.
Code In Image
function area = MitchellLitvinov_areaCalc(n)
% create random coordinate vectors, with bounds from (3, 14)
x = rand(n, 1) * 11 + 3;
y = rand(n, 1) * 11 + 3;
% find every point that is inside of oracle
inOracle = oracle([x y]);
% calculate the proportion, and multiply total area by proportion to find area
% of oracle
numPointsInOracle = nnz(inOracle);
area = numPointsInOracle/n * (11*11);
% create variable to store number of points in the area, and create a
% matrix with size [numPoints, 2] to hold x and y values
oracleCoordinates = zeros(numPointsInOracle, 2);
% HERE IS WHERE I NEED ASSISTANCE!!!!!!!!!
% find the points that are in the oracle shape
index = 0; % start index at 0 % is the index of our oracleCoordinates matrix
for i = 1:n % have to go through every point again to get their index
% if point is inside oracle, increase index and record
% coordinates
if (inOracle(i) == 1) % see if point is in oracle
index = index + 1;
oracleCoordinates(index, 1) = x(i, 1);
oracleCoordinates(index, 2) = y(i, 1);
end
end
% plot all points inside the oracle
scatter(oracleCoordinates(:,1), oracleCoordinates(:,2))
title("Oracle Shape")
xlim([3, 14]);
ylim([3, 14]);
end
Yes, even with near maximum memory usage, the code will run fairly quickly. But I want it to be fully vectorized simply for speed reasons, and if I need to repurpose this code for imaging. Currently, to calculate the area I am using vectors, but to actually reproduce an image, I need to create a separate storage matrix, and manually use indexing/appending to then transfer over the points inside the oracle function. I was wondering if there were any direct "shortcuts" to make my plotting a bit faster.
You can use an array as the index to select certain items from another array. For example, using your variable names:
oracleCoordinates(:,1) = x(inOracle == 1);
oracleCoordinates(:,2) = y(inOracle == 1);
This should give the same result as the code in your question, without using a loop.

Use of Matlab find function for getting index of a vertex using its coordinates

I have a matrix 50943x3 that contains vertices of a surface mesh.I want to find the index of a certain vertex using its coordinates (x,y,z).
I tried the Matlab function find but it return an empty matrix 0-by-1.
Thanks in advance,
Cheers
Your attempt probably does not work because of floating point rounding errors. You can read more about it here. You could look into the the eps function, or just use this example:
% Your matrix
M = randn(50943 , 3);
% The coordinates you are looking for
P = [0,0,0];
% Distance between all coordinates and target point
D = sqrt(sum((M - bsxfun(#minus,M,P)).^2,2));
% Closest coordinates to target
[~ , pos] = min(D);
% Display result
disp(M(pos , :))
Try the following:
mat = randi(30,50943,3);
vec = [1,2,3];
% R2106b+ code
ind = find(all(mat==vec,2));
% or: explicit expansion, works with all versions
ind = find(all(bsxfun(#eq,mat,vec),2));
What it does:
== or eq will check if coordinates are equal (gives a [50943x3] bool matrix)
all will return true only if all coordinates are equal
find returns the index of all non zero elements
This works only for an exact match (hence the integer coordinates picked with randi).
Since the answer is already accepted, I'll add #Zep answer that provide a solution to get the nearest point, which seem to be what was initially sought.
[min_dist,ind_nearest] = min(sum(bsxfun(#minus,mat,vec).^2,2)); % index to the nearest point

How to create matrix of nearest neighbours from dataset using matrix of indices - matlab

I have an Nx2 matrix of data points where each row is a data point. I also have an NxK matrix of indices of the K nearest neighbours from the knnsearch function. I am trying to create a matrix that contains in each row the data point followed by the K neighbouring data points, i.e. for K = 2 we would have something like [data1, neighbour1, neighbour2] for each row.
I have been messing round with loops and attempting to index with matrices but to no avail, the fact that each datapoint is 1x2 is confusing me.
My ultimate aim is to calculate gradients to train an RBF network in a similar manner to:
D = (x_dist - y_dist)./(y_dist+(y_dist==0));
temp = y';
neg_gradient = -2.*sum(kron(D, ones(1,2)) .* ...
(repmat(y, 1, ndata) - repmat((temp(:))', ndata, 1)), 1);
neg_gradient = (reshape(neg_gradient, net.nout, ndata))';
You could use something along those lines:
K = 2;
nearest = knnsearch(data, data, 'K', K+1);%// Gets point itself and K nearest ones
mat = reshape(data(nearest.',:).',[],N).'; %// Extracts the coordinates
We generate data(nearest.',:) to get a 3*N-by-2 matrix, where every 3 consecutive rows are the points that correspond to each other. We transpose this to get the xy-coordinates into the same column. (MATLAB is column major, i.e. values in a column are stored consecutively). Then we reshape the data, so every column contains the xy-coordinates of the rows of nearest. So we only need to transpose once more in the end.

extracting matrix values from another matrix

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.

Octave time series Moving average

I have a matrix with each column represents a feature over time. I need to find the moving average of these values with a given window size.
Is there a function like the one in MATLAB?
output = tsmovavg(vector, 's', lag, dim)
You can use the FILTER function. An example:
t = (0:.001:1)'; %#'
vector = sin(2*pi*t) + 0.2*randn(size(t)); %# time series
wndw = 10; %# sliding window size
output1 = filter(ones(wndw,1)/wndw, 1, vector); %# moving average
or even use the IMFILTER and FSPECIAL from the Image Package
output2 = imfilter(vector, fspecial('average', [wndw 1]));
One final option is using indexing (not recommended for very large vector)
%# get indices of each sliding window
idx = bsxfun(#plus, (1:wndw)', 0:length(vector)-wndw);
%'# compute average of each
output3 = mean(vector(idx),1);
Please note the difference in padding: output1(wndw:end) corresponds to output3