Matlab - Assign a matrix to an index of a variable - matlab

how can I get a matrix out of cell array?
here is my cell array:
d{1} = [[1 1]; [2 2]; [3 3]]
d{2} = [[1 2]; [2 3]]
I want to get the first matrix out of d{1} which should give me [1 1] but I tried this:
d{1}(1) and It only gives me the first element in the cell. How can I get it to return these cells as a matrix?

As you want to access both columns of the first row. So, simply do this: d{1}(1,:)

Related

Merging elements of different cells

Suppose, we have a cell array consisting of ids and one attribute, e.g.
A{1,1}=[1 2;2 4]
A{1,2}=[2 3 5;8 5 6]
Now, I'd like to have a final output consisting of unique ids of two cells (first row values) and corresponding columns have attribute value of each cell separately.
i.e.
C =
[1] [ 2]
[2] [1x2 double] % 4 in first cell and 8 in second cell
[3] [ 5]
[5] [ 6]
it seems that it's not possible to use something like C=[unique(A{1,:}(1,:)')]. Any help is greatly appreciated.
Assuming that each cell has two rows and a variable amount of columns where the first row is the ID and the second row is an attribute, I'd consolidate all of the cells into a single 2D matrix and use accumarray. accumarray is very suitable here because you want to group values that belong to the same ID together and apply a function to it. In our case, our function will simply place the values in a cell array and we'll make sure that the values are sorted because the values that are grouped by accumarray per ID come into the function in random order.
Use cell2mat to convert the cells into a 2D matrix, transpose it so that it's compatible for accumarray, and use it. One thing I'll need to note is that should any IDs be missing, accumarray will make this slot empty. What I meant by missing is that in your example, the ID 4 is missing as there is a gap between 3 and 5 and also the ID 6 between 5 and 7 (I added the example in your comment to me). Because the largest ID in your data is 7, accumarray works by assigning outputs from ID 1 up to ID 7 in increments of 1. The last thing we would need to tackle is to eliminate any empty cells from the output of accumarray to complete the grouping.
BTW, I'm going to assume that your cell array consists of a single row of cells like your example.... so:
%// Setup
A{1,1}=[1 2;2 4];
A{1,2}=[2 3 5;8 5 6];
A{1,3}=[7;8];
%// Convert row of cell arrays to a single 2D matrix, then transpose for accumarray
B = cell2mat(A).';
%// Group IDs together and ensure they're sorted
out = accumarray(B(:,1), B(:,2), [], #(x) {sort(x)});
%// Add a column of IDs and concatenate with the previous output
IDs = num2cell((1:numel(out)).');
out = [IDs out];
%// Any cells from the grouping that are empty, eliminate
ind = cellfun(#isempty, out(:,2));
out(ind,:) = [];
We get:
out =
[1] [ 2]
[2] [2x1 double]
[3] [ 5]
[5] [ 6]
[7] [ 8]
>> celldisp(out(2,:))
ans{1} =
2
ans{2} =
4
8
If you'd like this done on a 2D cell array, where each row of this cell array represents a separate instance of the same problem, one suggestion I have is to perhaps loop over each row. Something like this, given your example in the comments:
%// Setup
A{1,1}=[1 2;2 4];
A{1,2}=[2 3 5;8 5 6];
A{1,3}=[7;8];
A{2,1}=[1 2;2 4];
A{2,2}=[1;7];
%// Make a cell array that will contain the output per row
out = cell(size(A,1),1);
for idx = 1 : size(A,1)
%// Convert row of cell arrays to a single 2D matrix, then transpose for accumarray
B = cell2mat(A(idx,:)).';
%// Group IDs together and ensure they're sorted
out{idx} = accumarray(B(:,1), B(:,2), [], #(x) {sort(x)});
%// Add a column of IDs and concatenate with the previous output
IDs = num2cell((1:numel(out{idx})).');
out{idx} = [IDs out{idx}];
%// Any cells from the grouping that are empty, eliminate
ind = cellfun(#isempty, out{idx}(:,2));
out{idx}(ind,:) = [];
end
We get:
>> out{1}
ans =
[1] [ 2]
[2] [2x1 double]
[3] [ 5]
[5] [ 6]
[7] [ 8]
>> out{2}
ans =
[1] [2x1 double]
[2] [ 4]
>> celldisp(out{1}(2,:))
ans{1} =
2
ans{2} =
4
8
>> celldisp(out{2}(1,:))
ans{1} =
1
ans{2} =
2
7

How to get a unique array value in Matlab?

I have array value like this snippet below:
a = { [1 2 4]; [3 5 6 7]; [1 2 4]; [3 5 6 7]; [8 9]; []};
I am trying Matlab to get array value like this
a = { [1 2 4]; [3 5 6 7];[8 9]};
basic solution for finding uniques
unique(cellfun(#(x)(mat2str(x)),a,'uniformoutput',false))
This can be found here actually.
Complicating factors
Technically the empty cell at the end is also unique, perhaps you want to remove it separately like so:
a(cellfun(#isempty,a)) = []
Currently you get strings as output, this can be solved like so:
[~, idx] = unique(cellfun(#(x)(mat2str(x)),a,'uniformoutput',false))
a(idx)
I personally think that this is harder than it should be.
Summary
You can get your desired output like so
a(cellfun(#isempty,a)) = []
[~, idx] = unique(cellfun(#(x)(mat2str(x)),a,'uniformoutput',false))
a(idx)

Searching a cell array of vectors and returning indices

I have a 3000x1 cell array of vectors of different lengths and am looking for a way to search them all for a number and return the cell indices for the first and last occurrence of that number.
So my data looks like this:
[1]
[1 2]
[1 2]
[3]
[6 7 8 9]
etc
And I want to my results to look like this when I search for the number 1:
ans = 1 3
All the indices (e.g. [1 2 3] for 1) would also work, though the above would be better. So far I'm unable to solve either problem.
I've tried
cellfun(#(x) x==1, positions, 'UniformOutput', 0)
This returns a logical array, effectively putting me back at square 1. I've tried using find(cellfun...) but this gives the error undefined function 'find' for input arguments of type 'cell'. Most of the help I can find is for searching for strings within a cell array. Do I need to convert all my vectors to strings for this to work?
C = {[1]
[1 2]
[1 2]
[3]
[6 7 8 9]}; %// example data
N = 1; %// sought number
ind = cellfun(#(v) any(v==N), C); %// gives 1 for cells which contain N
first = find(ind,1);
last = find(ind,1,'last');
result = [ first last ];

Given a cell array of vectors, delete vectors that are subsets of any other vector

I wanna delete all the subsets of cell c, suppose I have 6 cell vectors: c{1}=[1 2 3]; c{2}=[2 3 4];
c{3}=[1 2 3 4 5 6]; c{4}=[2 3 4 7]; c{5}=[2 3 7]; c{6}=[4 5 6]; then I wanna delete [1 2 3], [2 3 4] and [4 5 6]. I used two for loops to find all these subsets, but it's too slow for large datasets, is there any simple way can do this?
The following code removes a vector if it's a subset of any other vector. The approach is very similar to my answer to this other question:
n = numel(c);
[i1 i2] = meshgrid(1:n); %// generate all pairs of cells (their indices, really)
issubset = arrayfun(#(k) all(ismember(c{i1(k)},c{i2(k)})), 1:n^2); %// subset?
issubset = reshape(issubset,n,n) - eye(n); %// remove diagonal
c = c(~any(issubset)); %// remove subsets
Note that, in your example, [2 3 7] should also be removed.
You could find the cells that are exact matches for a particular input vector s1 using the following approach:
indx = find(cell2mat(cellfun(#(x)strcmp(num2str(x),num2str(s1)),c,'un', 0)));
You can then loop over matches (which should now be a much smaller set), and remove them by setting their contents to an empty set:
for ii=1:length(indx)
c{:,ii} = [];
end

How can I insert each row of a matrix into cells in Matlab?

Suppose A = [1 2 3;4 5 6;7 8 9]
I want to convert it to B = [{[1,2,3]};{[4,5,6]};{[7,8,9]}]
How can I do that in an easy way?
You can use mat2cell function.
From the documentation:
C = mat2cell(A,dim1Dist,...,dimNDist) divides array A into smaller
arrays within cell array C. Vectors dim1Dist,...dimNDist specify how
to divide the rows, columns, and (when applicable) higher dimensions
of A.
You can do it like this:
A = [1 2 3; 4 5 6; 7 8 9];
B = mat2cell(A, [1 1 1], 3);
will give you:
B={[1 2 3];[4 5 6];[7 8 9]}
Documentation also says:
C = mat2cell(A,rowDist) divides array A into an n-by-1 cell array C,
where n == numel(rowDist).
So, if you are always going to split your matrix to rows, but not to columns, you can do it without the second parameter.
B = mat2cell(A, [1 1 1]);
A better, generalized way would be:
mat2cell(A, ones(1, size(A, 1)), size(A, 2));
You can't have a "matrix of cells" like your notation for B implied.
A cell array allows you to store "any data type" in the individual cells. You can't store a cell as a data type in an array.
So let's assume you meant to say you wanted B = {[1,2,3], [4,5,6], [7,8,9]};
If that is the case, then
B = cell(1,3);
for ii=1:3
B(ii) = {A(ii, :)};
end
should do the trick.
Note - edited based on Hadi's comment.