Remove negative digits from a cell array

2 次查看(过去 30 天)
Hi all.
If I have a number like that 1 1 4 1 5 6 4 2 -2 3 -2 3 6 1 1 -2 -2 -2 -2 9.
If I don't want the negative digits, how can I do it?
Thank you in advance for any possible answers.
Pedro

回答(1 个)

dpb
dpb 2023-4-17
移动:dpb 2023-4-17
There's no cell array in sight in the above and how do you want to eliminate them -- replace with something else or remove entirely so the array is smaller?
x{1}=[1 1 4 1 5 6 4 2 -2 3 -2 3 6 1 1 -2 -2 -2 -2 9]
x = 1×1 cell array
{[1 1 4 1 5 6 4 2 -2 3 -2 3 6 1 1 -2 -2 -2 -2 9]}
Remove
x{:}
ans = 1×20
1 1 4 1 5 6 4 2 -2 3 -2 3 6 1 1 -2 -2 -2 -2 9
x{1}>0
ans = 1×20 logical array
1 1 1 1 1 1 1 1 0 1 0 1 1 1 1 0 0 0 0 1
x{1}(x{1}>0)
ans = 1×14
1 1 4 1 5 6 4 2 3 3 6 1 1 9
x={x{1}(x{1}>0)}
x = 1×1 cell array
{[1 1 4 1 5 6 4 2 3 3 6 1 1 9]}
You first have to dereference the cell array to get to the content, then do the logical addressing on that array -- then put that back into the cell.
If it is a cell array, then @cellfun will be helpful
  3 个评论
Image Analyst
Image Analyst 2023-4-17
编辑:Image Analyst 2023-4-17
Or a double matrix? If it's a matrix, you can't "remove" elements because it must remain rectangular. You can't have matrices with "ragged" right or bottom edges because rows or columns were shifted, and you can't have "holes" in the matrix, though you can assign NaN to those locations if you want.
dpb
dpb 2023-4-17
编辑:dpb 2023-4-17
I had @Image Analyst's response in preparation but a meeting pulled me away before posting...specifically what I was going to illustrate is something that is the best approximation one can make other than insertion of the missing value (NaN for double) is to create a cell array
N=8; % dataset small enough to observe
x=randi([-2 9],N) % create a set of data
x = 8×8
3 8 -1 0 -2 8 1 3 9 3 1 -2 1 7 3 -2 3 1 5 0 8 1 9 0 -1 5 9 1 2 9 7 9 4 4 9 8 -1 6 -2 6 4 2 -2 5 7 4 9 -2 9 7 6 9 8 7 3 4 0 5 5 2 5 -1 1 -1
x=num2cell(x,2) % turn into set of row cell arrays
x = 8×1 cell array
{[3 8 -1 0 -2 8 1 3]} {[9 3 1 -2 1 7 3 -2]} {[ 3 1 5 0 8 1 9 0]} {[ -1 5 9 1 2 9 7 9]} {[4 4 9 8 -1 6 -2 6]} {[4 2 -2 5 7 4 9 -2]} {[ 9 7 6 9 8 7 3 4]} {[0 5 5 2 5 -1 1 -1]}
cellfun(@(c)c(c>=0),x,'uniformoutput',0) % keep only positive values each cell
ans = 8×1 cell array
{[ 3 8 0 8 1 3]} {[ 9 3 1 1 7 3]} {[3 1 5 0 8 1 9 0]} {[ 5 9 1 2 9 7 9]} {[ 4 4 9 8 6 6]} {[ 4 2 5 7 4 9]} {[9 7 6 9 8 7 3 4]} {[ 0 5 5 2 5 1]}
Now you have only the positive values left, but it isn't in a regular 2D array any more (and can't be), but it meets the request to remove the negative values.
Depending upon what it is that is/are the next step(s), it may be simpler to just treat the missing values instead; functions like mean, etc., all have flags to 'omitnan'.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by