Access subset of elements in a cell
26 views (last 30 days)
Show older comments
I have created the following cell C from reading a txt file.
{["0719-3" ]} {["0729-2" ]} {["0742-5" ]} {["0742-6" ]} {["0744-5" ]} {["0744-6" ]}
{84444×4 double} {84444×4 double} {84444×4 double} {84444×4 double} {84444×4 double} {84444×4 double}
I want to switch the sign of the 2nd to 4th colums of each matrix (second row). Is there any way I can access all the submatrix (:,2:4) in the cell? I habe tried C{2,:}(:,2:4) (I was hoping to do something like C{2,:}(:,2:4) = -C{2,:}(:,2:4)but it does not work.
0 Comments
Accepted Answer
Andres
on 15 May 2020
When typing
C{2,:}(:,2:4)
you are probably getting the error message "Expected one output from a curly brace or dot indexing expression, but there were 6 results" which pretty much explains what is happening. Note that
C{2,1}(:,2:4)
does not error.
You could use cellfun on C(2,:) as follows:
C = [{"A1"},{"A2"},{"A3"}; repmat({magic(4)},1,3) ]; % sample cell array
C(2,:) = cellfun(@(x) x.*[1,-1,-1,-1], C(2,:), 'UniformOutput', false);
>> C
C =
2×3 cell array
{["A1" ]} {["A2" ]} {["A3" ]}
{4×4 double} {4×4 double} {4×4 double}
>> C{2,1}
ans =
16 -2 -3 -13
5 -11 -10 -8
9 -7 -6 -12
4 -14 -15 -1
3 Comments
Andres
on 15 May 2020
Edited: Andres
on 15 May 2020
@(x) x.*[1,-1,-1,-1]
is the anonymous function that is applied to each element of the cell array via cellfun
x is just the input argument of the anonymous function, so it represents any element of the cell array passed to cellfun, i.e. each of the 84444×4 double arrays in C(2,:) here.
'UniformOutput' is one of the name-value pair arguments for cellfun that has to be set to false if the function applied does not return a scalar. This is the case here as the function returns an N×4 array.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!