Access subset of elements in a cell
22 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Andres
2020-5-15
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 个评论
Andres
2020-5-15
编辑:Andres
2020-5-15
@(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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!