Access subset of elements in a cell

조회 수: 19 (최근 30일)
Luigi
Luigi 2020년 5월 15일
댓글: Luigi 2020년 5월 15일
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.

채택된 답변

Andres
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
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.
Luigi
Luigi 2020년 5월 15일
Thx a lot!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by