MATLAB Answers

Complete cell positions with NaN

조회 수: 1(최근 30일)
Alejandro Fernández
Alejandro Fernández 2020년 8월 17일
편집: Bruno Luong 2020년 8월 17일
Hello, I will try to give an example to illustrate what I want to achieve, it starts from a cell type matrix with 3 rows like the following one:
AA{1,1} = [0 0 1 0 0 0 0];
AA{2,1} = [0 1 0 0];
AA{3,1} = [0 0 0 1 0 0 0 0 0];
And I want to obtain the following resoult:
BB{1,1} = [NaN -2 -1 0 1 2 3 4 NaN];
BB{2,1} = [NaN NaN -1 0 1 2 NaN NaN NaN];
BB{3,1} = [-3 -2 -1 0 1 2 3 4 5];
Now I'm going to explain a little bit how to get to that BB cell:
For each component of the cell the positions behind 1 will be negative, the position taken by 1 will be zero and to the right of 1 will be positive. This step can be done thanks to [1] but in the case of independent vectors, without being in cells.
Then we would have to fill in with NaN so that the positions that take a value of 0 are aligned, establishing the most negative and most positive value of the cell, as you can see the result in the BB matrix.
It would also help me (although it wouldn't be the best) if the result was a matrix like this:
BB =
[NaN -2 -1 0 1 2 3 4 NaN
NaN NaN -1 0 1 2 NaN NaN NaN];
-3 -2 -1 0 1 2 3 4 5];

채택된 답변

Bruno Luong
Bruno Luong 2020년 8월 17일
편집: Bruno Luong 2020년 8월 17일
AA{1,1} = [0 0 1 0 0 0 0];
AA{2,1} = [0 1 0 0];
AA{3,1} = [0 0 0 1 0 0 0 0 0];
i1=cellfun(@(a) find(a==1,1), AA);
maxi1=max(i1);
lgt=cellfun(@length,AA);
idx = arrayfun(@(lgt,i1) (1:lgt)-i1, lgt, i1, 'unif', 0);
col = cellfun(@(idx) idx+maxi1, idx, 'UniformOutput', false);
row = arrayfun(@(r) r+zeros(size(idx{r})), 1:size(idx,1), 'UniformOutput', false);
COL=[col{:}];
ROW=[row{:}];
IDX=[idx{:}];
BB = accumarray([ROW(:) COL(:)],IDX(:),[],[],NaN);
CC=num2cell(BB,2);
CC{:}
  댓글 수: 1
Alejandro Fernández
Alejandro Fernández 2020년 8월 17일
Wow thank you so much!!

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

추가 답변(0개)

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by