Indexing a cell array with variable number of dimensions with a vector - arrays

In MATLAB, have an N-dimensional cell C, where N is an integer only determined at runtime. How do I access a specific element of C with a vector variable id? For example, with N=3 and id=[1,5,2], how to programmatically get the content of c{1,5,2}? I cannot hard-code it as c{id(1),id(2),id(3)} since N is only fixed at runtime.

If id is a cell array, then you can use sub2ind for this by taking advantage of the comma separated list syntax ,i.e. {:}, to send a variable number of inputs to sub2ind
id = {1,5,2};
ind = sub2ind(size(C), id{:})
c{ind}
if id isn't a cell array (and for some reason can't be created as one), then use num2cell to convert it.

Related

Get specific cells from a cell array

I have a numeric array sized 1000x1 which have values 0 and 1, called conditionArray.
I have a cell array called netNames with the same size (1000x1) and its cells contain string values (which are name of some circuit nets).
I want to extract net names which from netNames which their pairwise condition bit is 1 in conditionArray.
E.g. if conditionArray(100) is equal to extract its net name from netNames{100}.
Output of this process can be stored in an string array or cell array.
Are there any ways to do this operation with pairwise operations or I should use a for statement for this?
You shall check out cellfun in Matlab anytime you want to manipulate each element inside a cellarray without using a for loop.
As I understand, you have:
N = 1000;
% an array with 0s and 1s (this generates random 0s and 1s):
conditionArray = randi([0,1],N);
% a cell array with strings (this generates random 5-character strings):
netNames = cell(N);
netNames = cellfun(#(c)char(randi([double('a'),double('z')],1,5)), netNames, 'UniformOutput',false);
To extract the elements from netNames where conditionArray is 1, you can do:
netNames(conditionArray==1)
This uses logical indexing into the cell array.

Calculating standard deviation on data stored in a cell array of cell arrays

I have a cell array A Mx3 in size where each entry contains a further cell-array Nx1 in size, for example when M=9 and N=5:
All data contained within in any given cell array is in vector format and of equal length. For example, A{1,1} contains 5 vectors 1x93 in size whilst A{1,2} contains 5 vectors 1x100 in size:
I wish to carry out this procedure on each of the 27 cells:
B = transpose(cell2mat(A{1,1}));
B = sort(B);
C = std(B,0,2); %Calculate standard deviation
Ultimately, the desired outcome would be, for the above example, 27 columns (9x3) containing the standard deviation results (padded with 0 or NaNs to handle differing lengths) printed in the order A{1,1}, A{1,2}, A{1,3}, A{2,1}, A{2,2}, A{2,3} and so forth.
I can do this by wrapping the above code into a loop to iterate over each one of the 27 cells in the correct order however, I was wondering if there was a clever cellfun or more succinct method to accomplish this particularly without the use of a loop?
You should probably realize that cellfun is essentially a glorified for loop over cells. There's simply extra error checking and all that to ensure that the whole thing works. In any case, yes it's possible to do what you're asking in a single cellfun call. Note that I am simply going to apply the same logic as you would have in a for loop with cellfun. Also note that because you're using cell arrays, you have no choice but to iterate over the entire master cell array. However, what you'll want to do is pad each resulting column vector in each output in the final cell array so that they all share the same length. We can do that with another two cellfun calls - one to determine the largest vector length and another to perform the padding operation.
Something like this could work:
% Step #1 - Sort the vectors in each cell array, then find row-wise std
B = cellfun(#(x) std(sort(cell2mat(x).'), 0, 2), A, 'un', 0);
% Step #2 - Determine the largest length vector and pad
sizes = cellfun(#numel, B);
B = cellfun(#(x) [x; nan(max(sizes(:)) - numel(x), 1)], B, 'un', 0);
The first line of code takes each element in A, converts each cell element into a N x 5 column matrix (i.e. cell2mat(x).'), we then sort each column individually with sort, then take the standard deviation row-wise. Because the output is ultimately a vector, we must make sure that the 'UniformOutput' flag is 0, or 'un=0'. Once we complete the standard deviation calculation, we determine the total number of elements for each resulting column vector for all cell elements, determine the largest size then use another cellfun call to pad these vectors so they all match the same size.
To finally get your desired output, you need to transpose the cell array, then unroll the elements in column major order. Remember that MATLAB accesses things in column major, so a common trick to get things in row-major (what you want) as opposed to column major is to first transpose, then unroll in column-major fashion to perform a row-major readout. Doing this in one line is tricky, so you'll need to not only transpose the cell array, you must use reshape to ensure that the elements are read out in row major format, but then ensuring that the result is placed in a row of cells, then call cell2mat so you can piece these vectors together. The final result should be a 27 column matrix where we have pieced all of these vectors together in a single row-wise fashion:
C = cell2mat(reshape(B.', 1, []));

Matlab: Refer to multiple, non consecutive elements

In Matlab is there any way to refer to multiple, non consecutive elements in a 1 dimensional array in the same line, eg. something like:
mean(strength(1:4,17:20))
I want to calculate the mean of 1st to 4th elements and the 17th to 20th elements in an array called strength etc. Except obviously a comma wouldn't work, because that would be double indexing, as if it was a matrix, when it's 1D. Is there another symbol you could use in place of the comma to do this, or would you need another technique to do this?
Like Andras says in his comment, you need a vector of the indices you wish to include in the calculation of the mean:
Just as you would reference the ith value of a vector with strength(i), you can have a vector instead of i, which will give you all of the specified values as another vector:
indexVector = [1:4, 17:20];
values = strength(indexVector);
This will give you a 1D vector of length 8 containing values 1:4 and 17:20 of the original strength vector, which would allow you to use mean(strength).
You can bypass writing these to variables, and just use:
mean(strength([1:4, 17:20]))

Save unlimited matrix from cell arrays

I get a cell array which contains 103 cells of different dimensions. Each cell of my cell array represents a matrix and it can be displayed as an image. How can I extract each cell (ie each matrix) in a for loop?
I know how to do that one by one but not for the whole cell :
image1 = cellArray{1}; % extract matrix 1 (on 103) from the cell array #1
image2 = cellArray{2}; % and so on
Thanks for your help
The easiest way to loop through your cell array and apply to same function to every cell is to use cellfun. If your function returns a scalar e.g.
f = #(x)max(:)
then it's as simple as
cellfun(f, cellArray)
Note that f above is an anonymous function (or rather a function handle to an anonymous function), but more likely your function will be in its own m-file in which case you need to use the # operator:
cellfun(#f, cellArray)
Lastly, if your output is not a scalar then call
cellfun(#f, cellArray, 'uni' 0)

Matlab: Delete the item in an N-dimensional array whose Nth dimension is 1, where N is unknown?

I have an N-dimensional array of items whose last dimension is the index of the array.
For example, if the array A contained images, then A(:,:,:,1) would be the first image, A(:,:,:,2) would be the second image, and so forth.
Similarly, if the array just contained integers, then A(:,1) would be the first integer, A(:,2) would be the second integer, and so forth.
-=-=-=-
What I'm trying to do is delete the first item from A when I do not know ahead of time what dimensionality it is.
If A contains images, I want to do this:
A(:,:,:,1) = [];
If A contains integers, I want to do this:
A(:,1) = [];
The problem is since I don't know what dimensionality it is, I don't know how many colons to put, and I don't know how to denote "N-1 colons here" in Matlab.
I'm hoping there is a programmatic way to do this, but I frankly have no idea what to search for if this is possible.
You can either use cell to comma-separated list expansion:
%// Build cell: {':', ':', ..., ':', [1]}
I(1:ndims(A)-1) = {':'};
I{ndims(A)} = 1;
%// Expand cell to comma separated list and delete:
A(I{:}) = [];
Or convert to cell using num2cell and then convert back using cell2mat:
C = num2cell(A,1:ndims(A)-1);
A = cell2mat(C(2:end));
I guess that unless you really need n-dimensional arrays, doing this with a cell array of n-1 dimensional arrays instead (as is C in the above code) should be a smart move in terms of simplicity of notation.

Resources