MATLAB Answers

Complete cell positions with NaN

2 views (last 30 days)
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];

  0 Comments

Sign in to comment.

Accepted Answer

Bruno Luong
Bruno Luong on 17 Aug 2020
Edited: Bruno Luong on 17 Aug 2020
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 Comment

Sign in to comment.

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!