how to plot cell array with (31*1) dimensions in matlab? - matlab

I have a cell array with one column and thirty one rows, and I'm going to plot the array so that the horizontal axis changes from one to thirty one, and the vertical axis corresponds to values like peer to inside cell.
my cell array :
data2 =
31×1 cell array
'2.4392E-09' '2.6506E-09' '3.0690E-09' '4.0424E-09' '7.1719E-09'
'1.8084E-08' '6.0006E-08' '2.1621E-07' '7.7861E-07' '2.6695E-06'
'8.4323E-06' '2.3340E-05' '5.1783E-05' '1.1155E-04' '2.6871E-04'
'3.4549E-04' '2.6871E-04' '1.1155E-04' '5.1783E-05' '2.3340E-05'
'8.4323E-06' '2.6695E-06' '7.7861E-07' '2.1621E-07' '6.0006E-08'
'1.8084E-08' '7.1719E-09' '4.0424E-09' '3.0690E-09' '2.6506E-09'
'2.4392E-09'
and
i2 =
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
and part of my code for plot is:
i=1:1:31
data2=data(:,1)
i2=transpose(i);
i2=i2(:,1)
plot(i2,data2)

str2double converts numbers, stored as characters in cells of data2, to numeric (double) type. It is directly applicable on cell-arrays. If the required x-axis is the same as 1:numel(data2) then specifying it is not needed. So,
plot(str2double(data2));

This question aims at the very basics of MATLAB.
You have strings in a cell array. Access the content of cells with {} and convert it with str2doubleto numbers.
Further, keep the code clean and readable (data, data2 and i,i2) are not good variable names in no language... You don't need to transpose the vector but if you do, you can use the shortcut .'. Note that the . indicates that it is not a complex transpose
idx = 1:size(data,1)
cstr = data(:,1); % call the content of cells with {} / call a cell element with ()
num = str2double(cstr); % convert string to doubles/numbers
plot(idx.',num) % .' transposes an array/vector but in fact, you don't need it here

Related

Extract equal distance points from array - Matlab

I have an array of X,Y coordinates (closed object) of different sizes (numArrayLength, e.g., 25) and I wish to extract specific equally distances points based on a changeable number (subSetNum).
I have few issues that I will appreciate a help:
As the 1st and last content in the array are similar how can I avoid this point duplication?
I have a calculation issue, for example when I set subSetNum to 8 I get 1 4 7 10 13 16 19 22 25 but when it is set to 7 I get 1 5 9 13 17 21 25. Why?
Is there a way to do it without the loop?
Thanks.
Script:
clc;
clear;
numArrayLength=25; % Length of the array
subSetNum=8; % Selection points
numArray=rand(numArrayLength,2); % Array declaration, Y coordinate
numArray(numArrayLength)=numArray(1) %% Close object so Y(1) and Y(numArrayLength) are the same
numArray = numArray(1:end-1,:)
extractPoint=round(numArrayLength/subSetNum); %Number of points to extract
extractPointIndex=1:extractPoint:numArrayLength %Array index to extract
for n = 1:size(extractPointIndex)
numArray(extractPointIndex())
end

How to get unique pairs of numbers in matlab where both numbers have not repeated in the matrix before

I have an input matrix as below
all = [12 16;12 13;8 14;14 19;3 6;8 6;13 25;25 14;7 2];
I need the following output
output = [12 16;8 14;3 6;13 25;7 2];
The explanation for the output is as follows.
First row of input i.e. 12 16 is the first row in output as both the numbers have never been repeated before in the output matrix (obviously).
Second row of input i.e 12 13 is not needed as the number 12 is present in first row of output i.e repeated
Third row of input i.e 8 14 is second row of output as both the numbers have never been repeated before in the output matrix.
Fourth row of input i.e 14 19 is not needed as the number 14 is present in output i.e repeated
On similar lines
3 6 needed as both are not repeated,
8 6 not needed as both 8 and 6 are repeated,
13 25 needed as both are not repeated
25 14 not needed as both are repeated
7 2 needed as both are not repeated
I am not able to get any ideas to start. Any help will be appreciated.
Thanks!
One Liner Solution
res = all(arrayfun(#(ii) isempty(intersect(all(1:ii-1,:),all(ii,:))),1:size(all,1)),:);
Result
res =
12 16
8 14
3 6
7 2
Explanation
let's divide the one-liner into a more detailed and documented chunk of code:
%defines a function which validates for each index wheter the row is
%completely unique are not.
uniqueRowIndicator = #(ii) isempty(intersect(all(1:ii-1,:),all(ii,:)));
%finds all the unique row in the matrix
inds = arrayfun(uniqueRowIndicator,1:size(all,1));
%extracts the result from the returned indices
res = all(inds,:);
This assumes that if a row contains two equal values they count as repeated and thus the row should be removed.
Don't use all as a variable name, because that shadows a function:
A = [12 16;12 13;8 14;14 19;3 6;8 6;13 25;25 14;7 2]; % input matrix
[~, u] = unique(A.', 'first'); % unique values of linearized transposed A.
% In recent Matlab versions you an remove 'first '
M = false(flip(size(A))); % initiallize mask of values to be kept
M(u) = true; % fill values
output = A(all(M,1),:); % keep rows that only have non-repeated values
This gives
output =
12 16
8 14
3 6
7 2

Extract the same part of slices of a 3D matrix by using linear index

Indeed, my problem is a succession of my previous problem:
1) Extract submatrices, 2) vectorize and then 3) put back
Thanks to Dan and his ideas works perfectly for the purpose.
My new problem is this:
If I have a 3D matrix, 8 by 8 by 12, e.g. A = randn(8,8,12).
Let's see the linear index of the first slice:
From Dan's solution, I understand that A[4:6, 4:6, :] can extract the corresponding parts of all slices.
However, going back to my real situations, extracting parts by actually counting rows and columns seem not suit my purpose because my matrix size is huge and I do have many sub-matrices to be extracted.
So, I prefer to work on linear index and want to ask if there are any ways to work with this possibility.
Here is my trial:
By defining sub_group = [28 29 30 36 37 38 44 45 46], then A(sub_group) can extract sub-matrix from the first slice of the 3D matrix, A.
I understand that A(sub_group + 8*8*(n-1)) can extract the sub-matrix from the nth slice.
I aim to only work with my sub_group and then extract the same part of every slice.
Most importantly, I have to put back the sub-matrices after updating their values.
So, is there are any quick syntax for matlab to work for my purpose?
I appreciate for your help.
Approach #1
For cases like this when you need to calculate linear indices, you can use bsxfun as shown here -
%// Store number of rows in A as a variable
M = size(A,1)
%// Get start and offset linear indices for the first slice and thus sub_group
start_idx = (colstart-1)*M + rowstart
offset_idx = bsxfun(#plus,[0:rowstop - rowstart]', [0:colstop-colstart]*M) %//'
sub_group = reshape(start_idx + offset_idx,1,[])
%// Calculate sub_groups for all 3D slices
all_sub_groups = bsxfun(#plus,sub_group',[0:size(A,3)-1]*numel(A(:,:,1)))
Sample run -
A(:,:,1) =
0.096594 0.52368 0.76285 0.83984 0.27019
0.84588 0.65035 0.57569 0.42683 0.4008
0.9094 0.38515 0.63192 0.63162 0.55425
0.011341 0.6493 0.2782 0.83347 0.44387
A(:,:,2) =
0.090384 0.037262 0.38325 0.89456 0.89451
0.74438 0.9758 0.88445 0.39852 0.21417
0.032615 0.52234 0.25502 0.62502 0.0038592
0.42974 0.90963 0.90905 0.5676 0.88058
rowstart =
2
rowstop =
4
colstart =
3
colstop =
5
sub_group =
10 11 12 14 15 16 18 19 20
all_sub_groups =
10 30
11 31
12 32
14 34
15 35
16 36
18 38
19 39
20 40
Approach #2
For a quick syntax based solution, sub2ind could be suggested here. The implementation would look something like this -
[X,Y] = ndgrid(rowstart:rowstop,colstart:colstop);
sub_group = sub2ind(size(A(:,:,1)),X,Y);
[X,Y,Z] = ndgrid(rowstart:rowstop,colstart:colstop,1:size(A,3));
all_sub_groups = sub2ind(size(A),X,Y,Z);

Size of cell elements

I have five classes of data stored in a cell,
DataCell =
[74035x14 single] [8063x14 single] [7244x14 single] [6895x14 single] [2510x14 single]
I want to get the prior probabilities of each class,
So want it's pretty simple,
SumData = 74032 + 8063 + 7244 + 6895 + 2510;
prior = [74035 8063 7244 6895 2510] / SumData;
I was wondering if there is a way to avoid loop and get the answer.
Thanks,
Store the counts of the DataCell into an array, then "nomalize" it:
data_counts = cellfun(#(x) size(x,1), DataCell);
prior = data_counts / sum(data_counts(:));
The data_counts(:) is just a funny way of summing all the elements of data_counts, no matter what shape they're in.
To add to CST-Link's answer, cellfun has a special flag where if you specify 'size', you can determine the size of of elements inside each cell in a cell array. You simply specify which dimension you're measuring the size of and it'll return an array of elements that denote the size of each cell in a particular dimension. It will also respect whatever the shape of your cell array was before you call cellfun. For example, if you have a 2 x 2 cell array, after using 'size', it will return a 2 x 2 numeric matrix where each element is the size of the dimension you specified.
Therefore, do this:
data_counts = cellfun('size', DataCell, 1);
prior = data_counts / sum(data_counts(:));
To add to the data_counts(:) statement, this is MATLAB's way of unrolling a matrix. What this will do is that it transforms data_counts into a single vector, where it is composed of columns of A stacked on top of each other. For example, if you had a matrix like so:
A =
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Doing A(:) would give you:
1
5
9
13
2
6
10
14
3
7
11
15
4
8
12
16
However, if A is already a 1D array, then this has no effect at all. The only thing that it will do is that if your array was a row vector, this will transform the array so that it's column vector. If it was already a column vector, then this won't change anything. This is a neat trick to ensure that a 1D array is always a column vector.

Matlab column aggregation

Is there a function in MATLAB which allows to aggregate (or we can say sum) columns in a matrix per defined number of columns?
For example I have:
A =
1 2 3 4 5 6
9 10 11 12 13 14
17 18 19 20 21 22
I wish to aggregate every 2 columns, like this: col1+col2, and then col3+col4, and then col5+col6, so my output is:
A_agg =
3 7 11
19 23 27
35 39 43
I couldn't find a built-in function and was trying to write a for loop but I couldn't manage to do it since I am quite new to programming. Do you have any suggestions/solutions how this could be solved with a for loop, or maybe there is a built-in function?
Since sum operates down columns in a matrix, I first reshape A so that it has 2 rows and 9 columns, then sum down each column. Then reshape back to the desired output matrix A_agg.
A=[1 2 3 4 5 6
9 10 11 12 13 14
17 18 19 20 21 22]
[m,n]=size(A);
A_agg=reshape(sum(reshape(A',2,[])),m,[])'
You can use a combination of mat2cell and cellfun. You can use mat2cell to split up your matrices into individual 2 column chunks. Each chunk would be stored as a cell in a cell array. You can then use cellfun to take each cell and sum row-wise. After you're done, you can use cell2mat to convert back.
Using your example:
A = [1:6;9:14;17:22];
B = mat2cell(A, 3, [2 2 2]);
C = cellfun(#(x) sum(x,2), B, 'UniformOutput', false);
A_agg = cell2mat(C);
A_agg should thus give you:
A_agg =
3 7 11
19 23 27
35 39 43
Let's walk through the code slowly:
A is defined as we had before. B will be a cell array, and will segment your matrix into matrices of 2 columns per cell. The first parameter is the matrix you want to decompose (in our case A). The second parameter tells you how many rows each segment should have. Because we want all of the matrices to have the same number of rows, we thus supply one number which is 3. After, you specify the number of columns you want per matrix. Because there are 6 columns, we need 3 matrices, and so you'd specify a vector of [2 2 2].
C is the output of cellfun, where cellfun applies a function to every single element in a cell matrix. What you want to do here is for each cell (essentially each matrix), you want to sum row-wise. The first parameter is an anonymous function that takes in a matrix from each cell, and sums row-wise. The second parameter is the cell array we just created. You'll notice that we have an additional flag to set: UniformOutput. The reason why you have to set UniformOutput = false is because if you apply cellfun without that flag, the expected result at the end of the function you apply to each cell is scalar. Because we are outputting a column vector instead, we have to set this flag to false.
A_agg will thus aggregate all of your cells back to matrix form.
If you want to do this for any size matrix, bear in mind that there has to be an even amount of columns for this work. What I mean by even is that the number of columns has to be evenly divisible by 2. You would thus re-run the code like so:
B = mat2cell(A, size(A,1), 2*ones(1, size(A,2)/2));
C = cellfun(#(x) sum(x,2), B, 'UniformOutput', false);
A_agg = cell2mat(C);
Another possibility, if you have the Image Processing Toolbox, is to use blockproc. Let n denote the number of columns to be aggregated (2 in your example). Then:
A_agg = blockproc(A, [size(A,1) n], #(x) sum(x.data, 2));