I would like to use the linkage function in matlab with a custom distance.
My distance function is in the form:
Distance = pdist(matrix,#mydistance);
so given a
matrix = rand(132,18)
Distance will be a vector [1x8646];
D_matrix = squareform(Distance,'tomatrix');
is a matrix 132x132 contaning all the pairwise distances between te rows of matrix
How can I embed mydistance in linkage?
You can use a call to linkage like this:
Z = linkage(Data,'single','#mydistance')
where 'single' can also be any of the other cluster merge methods as described here: http://www.mathworks.com/help/stats/linkage.html.
In other words, just put your function handle in a string and pass it as the 3rd argument to linkage. You cannot use the 'savememory' function in linkage while using a custom distance function, however. This is causing me some frustration with my 300,000 x 6 dataset. I think the solution will be to project it to some space where euclidean distance is defined and meaningful but we'll see how that goes.
Besides using
tree = linkage(Data,'single','#mydistance')
like Imperssonator suggests, you can also use
dissimilarity = pdist(Data,#mydistance);
tree = linkage(dissimilarity,'single');
The latter has the benefit of allowing Data to be an object array with #mydistance using objects as arguments.
Related
Context
You have a 3D variable A
rng('default')
A = randi(100,5,7,3);
Problem
You want to get a column vector with all the values of a given slice along the third dimension of A, e.g.
Tmp = A(:,:,2);
out = Tmp(:);
Question
Is there a built in way to do this directly without having to use a temporary variable or a function (i.e. with a combination of brackets, ...)? The closest to what I look for I have found yet would be
out = reshape(A(:,:,2),[],1)
Which I find a bit "heavy". I was looking for something like (A(:,:,2))(:) but it doesn't work in MATLAB.
The fact that they added the input all in functions like any would suggest that there is not but I figured I'd still ask
I wanted to ask how to generate a data set in Matlab. I need it to test Feature Selection Algorithms on high dimensional data... The data set should be synthetic, multivariate and contain INTERACTING features.
Synthetic data sets like the MONKS problem is available on http://archive.ics.uci.edu/ml/datasets/MONK%27s+Problems .... unfortunately I have no clue how to visualize/generate and modify the data according to my need. The goal is to run an algorithm which detects interacting features.
I will be very thankful for a kind reply.
I'm not sure this is what you are looking for, but if I needed to do this, I would start by generating anonymous functions and generic variable names that I could apply randomly within a dataset.
For example, you could generate a dataset:
myData = rand(100,6);
and create a few functions which include interdependencies
interact = #(x) x*x;
interact2 = #(x) x*(x-1);
then create a random logical distribution
y = round(rand(100,1)); %(100 rows of random 0's or 1's)
go through the dataset and use the interact function on only rows where y is true
dataset(y == 1,:) = interact(dataset(y==1,:));
repeat the above with the other interaction functions you define if you desire. it would probably be useful to do this so that you can avoid row dependencies (see below) so generating a few datasets could be in order, i.e.
dataset2(y==1,:) = interact2(dataset(y==1,:));
A similar approach might be taken with variables (in the example set it shows some categorical variables).
myVariable = repmat('data', 100, 1);
listofvariables = genvarname(cellstr(myVariable));
y = round(rand(100,1)); % logical index for the data
randomly select a generic variable to repeat
applyvar = round(rand(1,1)*100);
selectedVariable = listofvariables(applyvar);
replace indices of the variable list with your repeated variable
listofvariables(y == 1) = selectedVariable;
put together the dataset(s) in some order of your choosing
[cellstr(num2str(dataset(:,1))) listofvariables cellstr(num2str(dataset(:,2)) cellstr(num2str(dataset2(:,2))]
I'm interested in understanding the variety of zeroes that a given function produces with the ultimate goal of identifying the what frequencies are passed in high/low pass filters. My idea is that finding the lowest value zero of a filter will identify the passband for a LPF specifically. I'm attempting to use the [hz,hp,ht] = zplane(z,p) function to do so.
The description for that function reads "returns vectors of handles to the zero lines, hz". Could someone help me with what a vector of a handle is and what I do with one to be able to find the various zeros?
For example, a simple 5-point running average filter:
runavh = (1/5) * ones(1,5);
using zplane(runavh) gives an acceptable pole/zero plot, but running the [hz,hp,ht] = zplane(z,p) function results in hz=175.1075. I don't know what this number represents and how to use it.
Many thanks.
Using the get command, you can find out things about the data.
For example, type G=get(hz) to get a list of properties of the zero lines. Then the XData is given by G.XData, i.e. X=G.XData.
Alternatively, you can only pull out the data you want
X=get(hz,'XData')
Hope that helps.
I'm trying to create a function in MATLAB that takes a cartesian coordinate and converts it to polar.
function [homework5] = Cartesian(X,Y)
M = size(X,1)
for N=1:M
if X,Y;
r=sqrt(X^2+Y^2)
theta=atan(Y/X)
else
disp('input incorrect')
end
if r > 10
disp('Far from Origin')
else
disp('Close to Origin')
end
end
I'm extremely new to MATLAB and my searches for the answer and reading tutorials e.t.c have proved futile.
I have it to where it converts 1 coordinate just fine, but I need to convert multiple coordinates at once (hence the forloop) but I can't get it! The user needs to be able to enter an array like this: >>Cartesian = [2,3;4,5;6,7] and have each row converted.
Thanks for any help!
Don't you want to use MATLAB's function CART2POL?
If you look inside it just do this:
th = atan2(y,x);
r = hypot(x,y);
As for your code, it has many issues with syntax and logic.
First you don't need the loop. MATLAB specifically designed to work with vectors and matrices. You have to use element-wise multiplication, delition and power with .*, ./ and .^ operators.
Also if X,Y; doesn't do anything. Read the doc how to use if properly. You preallocate M but don't use it. The function is supposed to return homework5, but it's not defined in the function's body. You have to read about functions. Make sure the function is saved into the file with the same name Cartesian.m and in the current directory or in the MATLAB's path.
Suppose I have a column matrix pols containing vectors of [theta, rho, z].
Which means, if I have 9 such vectors, it will be a 9x3 matrix.
It is quite handy to have them arranged as such, because I can just feed any one of them to functions like pol2cart:
cart3 = pol2cart(pols(3,:));
and for a certain vector, I can find its components via the indices 1, 2, 3:
rho5 = pols(5,2);
But sometimes the matrix is actually within another wider matrix, and could be in the middle instead of the beginning, such that the above might become:
rho5 = pols(5,6);
In order to make the code more readable in case someone else has to maintain it, is there anyway to refer to an index via a unique name? Like
rho5 = pols(5).rho;
where it could be defined earlier that .rho maps to the column which has the value of rho.
I've ventured into converting matrices to cells then to array using mat2cell and cell2struct but it doesn't seem practical. Or, I could make an array of structs, but then I lose the ability to do pol2cart(pols), and instead must do
pol2cart(pols.theta, pols.rho, pols.z);
So to repeat the question: can I map the indices to unique names?
For the default MATLAB data types, no, you can't really do that. You could, however, create your own new data type (i.e. class object) to store your data. Within the class definition you would overload the subsref method to define how subscripted referencing (i.e. using (), {}, or .) behaves for your new object. This could get rather tricky with regards to dealing with arrays of objects, but it is possible.
Note that you would also have to create overloaded methods for all the existing functions you want to use on your new data type. Specifically, you would have to create a pol2cart method for your object that could internally call the built-in pol2cart function with the appropriate pieces of data from your object passed as arguments.
...And this brings me to a simpler solution for your current situation. Instead of making a whole new type of class object, you could create a structure array (or scalar structure of arrays) to store your data and simply create a new overloaded pol2cart function specifically for struct data types that will simplify the calling syntax.
I discuss more details of overloading functions for built-in data types in two other answers here and here. In short, you would create a folder called #struct and place it in a folder on your MATLAB path. In this #struct folder you would then put this overloaded function:
function varargout = pol2cart(polarCoordinates)
[varargout{1:nargout}] = pol2cart(polarCoordinates.theta, ...
polarCoordinates.rho, ...
polarCoordinates.z);
end
Note that this is a stream-lined version of the function, without error checks on the input, etc. Now, let's make some sample data:
pols = rand(9, 3); %# A 2-D array of data
polStruct = struct('theta', pols(:, 1), ... %# Convert it to a scalar
'rho', pols(:, 2), ... %# structure of arrays
'z', pols(:, 3));
And you could access the rho value of the fifth row as follows:
rho5 = pols(5,2);
rho5 = polStruct.rho(5);
If you wanted to convert from polar to cartesian coordinates, here's how you would do it for each data type:
[X,Y,Z] = pol2cart(pols(:,1), pols(:,2), pols(:,3)); %# Calls the built-in one
[X2,Y2,Z2] = pol2cart(polStruct); %# Calls the overloaded one
And you can check that they each give identical results as follows:
>> isequal([X Y Z],[X2 Y2 Z2])
ans =
1 %# True!
OK, the formal answer is probably "no" as given by woodchips above. However, if you really want to do something like that, you might be able to use a semi-hack. Specifically, you can define a class and overload an operator to achieve (almost) what you want. Unfortunately, I see that Matlab doesn't allow overloading ., so you have to use some other operator. (see edit below)
Just to give you the idea, here is a class that returns the i-th row of a matrix M by M^i.
classdef Test
properties
M;
end
methods
function this = Test(M)
this.M = M;
end
function res = mpower(this, i)
res = this.M(i, :);
end
end
end
And it can be run like this:
>> tmp = Test([1 2; 3 4]);
>> tmp^1
ans =
1 2
>> tmp^2
ans =
3 4
Use at your own risk! :)
Edit:
I was wrong above. As mentioned in gnovice's answer you can actually define the . operator for a custom class using method subsref.
No. You cannot do so. As simple as that.