Matlab: Counting the occurences of each element and sorting - matlab

I can use sort like this to sort elements in an array.
M = sort(A(:));
But is there a good method to sort the elements with its occurrences as well?
Like this:
ELEM = [10, 60, 30, 20]
OCCU = [30, 25, 10, 5]

You can do the above with combination of unique() and sort().
First extract only the unique values in the vector using unique() and group the same indices for occurrence.
Then just sort the values and you'll have what you asked above.

Related

Find a matching or closest value in an array (from a given value) [duplicate]

This question already has answers here:
How do I find values close to a given value?
(6 answers)
Closed 3 years ago.
How can I search and find, for a given target value, the closest value in an array?
For example here is my array:
0, 54, 10, 11, 152, 7
For example, when I search with the target value 6, the code shall return 7
% Array to search in, modified to have more than one closest value.
x = [0, 5, 10, 11, 152, 7];
% Target value.
target = 6;
Calculate absolute "distances" between each array element and the target value.
% Temporary "distances" array.
temp = abs(target - x);
Find the minimum "distance" value by min. Compare the temporary "distances" array to that minimum value (resulting in some binary array), and then use find to get the corresponding indices, which finally can be used to get the values from the original input array x.
% Find "closest" values array wrt. target value.
closest = x(find(temp == min(abs(target - x))))
The output looks like this:
closest =
5 7
You can use interp1 with the 'nearest' option:
V = [0, 54, 10, 11, 152, 7];
x = 6;
result = interp1(V,V,x,'nearest');

Matlab find the maximum and minimum value for each point of series of arrays (with negative values)

lets say that we have the next series of arrays:
A = [1, 2, -2, -24];
B = [1, 4, -7, -2];
C = [3, 1, -7, -14];
D = [11, 4, -7, -1];
E = [1, 2, -3, -4];
F = [5, 14, -17, -12];
I would like to create two arrays,
the first will be the maximum of each column for all arrays,
i.e.
Maxi = [11,14,-2 -1];
the second will be the minimum of each column for all arrays
i.e.
Mini= [1,1,-17 -24];
I am trying all day, using loops, with max, and abs but I cant make it work
in my problem have a matrix (100,200), so with the above example i am trying to easily approach the problem. The ultimate goal is to get a kinda fitting of the 100 y_lines of 200 x_points. The idea is to calculate two lines (i.e. max,min), that will be the "visual" boarders of all lines (maximum and minimum values for each x). The next step will be to calculate an array of the average of these two arrays, so in the end will be a line between all lines.
any help is more than welcome!
How about this?
Suppose you stack all the row vectors , namely A,B...,F as
arr=[A;B;C;D;E;F];% stack the vectors
And then use the max(), min() and mean() functions provided by Matlab. That is,
Maxi = max(arr); % Maxi is a row vector carrying the max of each column of arr
Mini = min(arr);
Meani = mean(arr);
You just have to stack them as shown above. But if you have 100s of row vectors, use a loop to stack them into array arr as shown above.

MATLAB: scan the row of a matrix and use values to search another matrix

I have matrix X and A where
X = [x1, y1, 1, 1; x2, y2, 1, 3; x3, y, 2, 4]
A = [1, 1, 0; 1, 3, 1; 1, 4, 2]
I want to:
1. scan the last two columns for every row in X (FYI, these two number combinations are unique)
2. find those values in the first two columns of A
3. get the value of the last column in that row of A.
For example, for the first row of X, I get 1 and 1, so I find 1 and 1 for the first two columns in A (which appears to be the first row), so the number I want to get is 0.
I think I can do it using a loop and a "find" function if it were just one number I'm working with, but I'm new to matlab and have trouble with a combination of two numbers. I would appreciate your help!
The ismember function may be what you're looking for, along with the () and : operators to extract columns from an array.
% Map rows in X to rows in A
[tf,loc] = ismember(X(:,[3 4]), A(:,[1 2]), 'rows');
% Grab the corresponding value from A
rslt = A(loc, 3);
Now you have a logical vector tf that indicates for each row in X whether it was found in A, and loc, which holds the corresponding indexes in to the rows of A for the ones that matched. Then you use those indexes to index in to A to pull out the "value" or dependent variable columns. These are vectorized operations, so it'll be faster than doing it with loops and find().
Read through the documentation for ismember, unique, paren, and the functions they reference to get more background on Matlab's functions for doing recordwise searching like this.

How to find all index pairs of unequal elements in vector (Matlab)

Lets say I have the following vector in Matlab:
V = [4, 5, 5, 7];
How can I list (in a n-by-2 matrix for example) all the index pairs corresponding to unequal elements in the vector. For example for this particular vector the index pairs would be:
index pairs (1, 2) and (1, 3) corresponding to element pair (4,5)
index pair (1, 4) corresponding to element pair (4,7)
index pairs (2, 4) and (3, 4) corresponding to element pair (5,7)
The reason I need this is because I have a cost-function which takes a vector such as V as input and produces a cost-value.
I want to see how does the random swapping of two differing elements in the vector affect the cost value (using this for steepest descent hill climbing).
The order of the index pairs doesn't also matter. For my purposes (1,2) is the same as (2,1).
For example if my cost-function was evalCost(), then I could have V = [4, 5, 5, 7] and
evalCost(V) = 14
whereas for W = [4, 7, 5, 5] the cost could be:
evalCost(W) = 10
How to get the list of "swapping" pair indexes in Matlab. Hope my question is clear =)
I don't understand the cost function part, but the first part is simple:
[a,b]=unique(V)
C = combnk(b,2)
C contains the indices, and V(C) the values:
C = combnk(b,2)
C =
1 2
1 4
2 4
V(C)
ans =
4 5
4 7
5 7
Use bsxfun and then the two-ouput version of find to get the pairs. triu is applied to the output of bsxfun to consider only one of the two possible orders.
[ii jj] = find(triu(bsxfun(#ne, V, V.')));
pairs = [ii jj];

Sorting in Matlab

I would like to sort elements in a comma-separated list. The elements in the list are structs and I would like the list to be sorted according to one of the fields in the struct.
For example, given the following code:
L = {struct('obs', [1 2 3 4], 'n', 4), struct('obs', [6 7 5 3], 'n', 2)};
I would want to have a way to sort L by the field 'n'. Matlab's sort function only works on matrices or arrays and on lists of strings (not even lists of numbers).
Any ideas on how that may be achieved?
Thanks,
Micha
I suggest you do this in three steps: Extract 'n' into an array, sort the array and consequently reorder the elements of the cell array.
%# get the n's
nList = cellfun(#(x)x.n,L);
%# sort the n's and capture the reordering in sortIdx
[sortedN,sortIdx] = sort(nList);
%# use the sortIdx to sort L
sortedL = L(sortIdx)
This is a bit of an aside, but if all of the structures in your cell array L have the same fields (obs and n in this case), then it would make more sense to store L as a 1-by-N structure array instead of a 1-by-N cell array of 1-by-1 structures.
To convert the 1-by-N cell array of structures to a 1-by-N structure array, you can do the following:
L = [L{:}];
Or, you can create the structure array directly using one call to STRUCT instead of creating the cell array of structures as you did in your example:
L = struct('obs',{[1 2 3 4],[6 7 5 3]},'n',{4,2});
Now the solution from Jonas becomes even simpler:
[junk,sortIndex] = sort([L.n]); %# Collect field n into an array and sort it
sortedL = L(sortIndex); %# Apply the sort to L
For what it's worth, here is the solution in Python:
L = [{'n': 4, 'obs': [1, 2, 3, 4]}, {'n': 2, 'obs': [6, 7, 5, 3]}]
L.sort(lambda a,b: a['n'].__cmp__(b['n']))
# L is now sorted as you wanted