This question already has answers here:
How to use cell arrays in Matlab?
(2 answers)
Closed 8 years ago.
Could any one tell me about the indexing of a cell Array? I've tried to google it but I could only find unsatisfied result (may be I'm not good in googling). For matrix indexing I found a good document which can be found here. For my case let take a simple example.
a = {ones(10)}
and I want to access the first element of a. Something like
a(1,1) % this will give a 10 x 10 matrix but i am not looking for it.
I can do it by changing it into a matrix like
a = cell2mat(a);
a(1,1)
ans = 1
but is there any direct way to access first element of cell array sub matrix.
To access the first element of a the first cell in a cell array, you may do:
a = {ones(10)};
a{1}(1)
If you have multidimensional cell arrays, with multidimensional numerical arrays inside it, you can do:
a{2,3}(4,5)
This will give you element (4,5) of cell (2,3).
You actually are accessing the first element of a, and it contains a matrix of 10×10 filled with ones.
Initializing a cell can be done by a = cell(10), and obtaining a certain value of the cell matrix is done with a{i,j}. See also the documentation.
For initializing a cell array with some values, see this question.
Related
This question already has answers here:
Use a vector as an index to a matrix
(3 answers)
Closed 4 years ago.
Is there a way in Matlab to select a matrix element based off the elements in a vector? I don't think my description is clear, but what I effectively want to do is something similar to:
A=zeros(3,3,3) %3d matrix
A(1,1,2)=5
b=[1,1,2]
A(b)=5
Meaning, some easy way to select one element from a matrix using the entries in a vector as arguments. This exact example does not work because the last line counts b as a single argument, not three. I could write A(b(1),b(2),b(3)) but what I'm really looking for here is if there's a nice way of doing.
Method 1: Use sub2ind to find the linear index
You can define a function called findLinearIndex such that it convert the vector elements to the linear index of A:
findLinearIndex = #(A,b) sub2ind(size(A), b(1), b(2), b(3))
A(findLinearIndex(A,b)) = 5
Method 2: Convert the vector to cell array by num2cell
Then, you can use {:} to get the index
b_cell = num2cell(b) ;
A(b_cell{:}) = 5
This question already has an answer here:
How do I create a 50x3 cell array from a 50x3 matrix. Keep just getting a 1x1 cell array with a 50x3 submatrix?
(1 answer)
Closed 9 years ago.
I'm trying to convert a 50 x 3 matrix into a 50 x 3 cell array, and I seem to be doing something wrong. Every time I try I'm left with a 1 x 1 cell array with the entire matrix in one cell.
You want NUM2CELL
num2cell(rand(50,3)); % gives 50x3 cell.
This question already has answers here:
matlab length of each element in cell array
(2 answers)
Closed 8 years ago.
Hi I have a cell array in matlab, where the cells are of differing lengths. how do i determine the average length of the cells.
I have tried:
mean(length(mycell{:});
however this is too many inputs for the mean function.
Thanks.
Use cellfun
mean( cellfun( #length, mycell ) )
BTW, for some of the builtin functions it might be better to write
mean( cellfun( 'length', mycell ) )
If your cell array contains only row vectors or only column vectors, there is an alternative method which doesn't use cellfun.
If your cell array contains row vectors: use either of these:
length([mycell{:}])/numel(mycell)
length(horzcat(mycell{:}))/numel(mycell)
If your cell array contains column vectors:
length(vertcat(mycell{:}))/numel(mycell)
This answer is faster than #Shai's if the cell array is small. For moderate or large sizes, or as a general answer, his solution (second version) is better.
I am using a cell array to contain 1x2 vectors of grid locations in the form [row, col].
I would like to check if another grid location is included in this cell array.
Unfortunately, my current code results in an error, and I cannot quite understand why:
in_range = ismember( 1, ismember({[player.row, player.col]}, proximity(:,1)) );
where player.row and player.col are integers, and proximity's first column is the aforementioned cell array of grid locations
the error I am receiving is:
??? Error using ==> cell.ismember at 28
Input must be cell arrays of strings.
Unfortunately, I have not been able to find any information regarding using ismember() in this fashion, only with cell arrays as strings or with single integers in each cell rather than vectors.
I have considered converting using num2str() and str2num(), but since I must perform calculations between the conversions, and due to the number of iterations the code will be looped for (10,000 loops, 4 conversions per loop), this method seems prohibitive.
Any help here would be greatly appreciated, thank you
EDIT: Why does ismember() return this error? Does it treat all vectors in a cell array as string arrays?
EDIT: Would there be a better / more efficient method of determining if a 1 is in the returned vector than
ismember( 1, ismember(...))?
I'm short of time at the moment (being Chrissy eve and all), so this is going to have to be a very quick answer.
As I understand it, the problem is to find if an x y coordinate lies in a sequence of many x y coordinates, and if so, the index of where it lies. If this is the case, and if you're interested in efficiency, then it is wasteful to mess around with strings or cell arrays. You should be using numeric matrices/vectors for this.
So, my suggestion: Convert the first row of your cell array to a numeric matrix. Then, compare your x y coordinates to the rows of this numerical matrix. Because you only want to know when both coordinates match a row of the numerical matrix, use the 'rows' option of ismember - it will return a true only on matching an entire row rather than matching a single element.
Some example code that will hopefully help follows:
%# Build an example cell array with coordinates in the first column, and random strings in the second column
CellOfLoc = {[1 2], 'hello'; [3 4], 'world'; [5 6], '!'};
%# Convert the first column of the cell array to a numerical matrix
MatOfLoc = cell2mat(CellOfLoc(:, 1));
%# Build an example x y coordinate location to test
LocToTest = [5 6];
%# Call ismember, being sure to use the rows option
Index = ismember(MatOfLoc, LocToTest, 'rows');
Note, if the indices in your cell array are in string form, then obviously you'll also need a call to str2num in there somewhere before you call ismember.
One other thing, I notice you're a new member, so welcome to the site. If you think this response satisfactorily answered your question, then please mark the question answered by clicking the tick mark next to this response.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I change the values of multiple points in a matrix?
I have a matrix A and three vectors of the same length, r, holding the indexes of the rows to assign to, c, holding the indexes of the columns to assign to, and v containing the actual values to assign.
What I want to get is A(r(i),c(i))==v(i) for all i. But doing
A(r,c)=v;
Doesn't yield the correct result as matlab interprets it as choosing every possible combination of r and c and assigning values to it, for instance
n=5;
A=zeros(n);
r=1:n;
c=1:n;
A(r,c)=1;
Yields a matrix of ones, where I would like to get the identity matrix since I want A(r(i),c(i))==1 for each i, that is only elements on the diagonal should be affected.
How can I achieve the desired result, without a for loop?
OK, I've found the answer - one needs to use linear indexing, that is convert the column\row pairs into a single index:
idx = sub2ind(size(A), r,c);
A(idx)=v;