How to replace the empty cells in a cell array by a 4-bits string?

조회 수: 9 (최근 30일)
Sarah A
Sarah A 2020년 1월 18일
댓글: Walter Roberson 2024년 11월 28일
Hello,
How to replace the empty cells " [ ] " in the attached matrix to a 4-bits string we can convert the whole array matrix to double.
For example,
if we have thw following row:
[ '0001', '0101' , '1010', [ ], [ ], [ ], '1111']
it becomes:
[0,0,0,1,0,1,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1]

채택된 답변

Akira Agata
Akira Agata 2020년 1월 19일
How about the following?
load('Key.mat');
idx = cellfun(@isempty,Key); % Find the indexes of empty cell
Key(idx) = {'0000'}; % Replace the empty cells with '0000'
  댓글 수: 3
Thomas Carpenter
Thomas Carpenter 2024년 11월 28일
편집: Thomas Carpenter 2024년 11월 28일
Using the optimised 'length' operation for cellfun - i.e ~cellfun('length',Key) - is generally more efficient than calling @isempty.
Walter Roberson
Walter Roberson 2024년 11월 28일
Timing test:
Key = num2cell(rand(100,100));
whos Key
Name Size Bytes Class Attributes Key 100x100 1280000 cell
Key(randi(100*100,50,1)) = {[]};
t1 = timeit(@() cellfun(@isempty,Key), 1)
t1 = 0.0055
t2 = timeit(@() ~cellfun('length',Key), 1)
t2 = 8.2372e-05
So the 'length' version is indeed faster.

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

추가 답변 (1개)

Stephan
Stephan 2020년 1월 18일
편집: Stephan 2020년 1월 18일
load('Key.mat');
Key1 = Key(:);
Key1 = reshape(replace(string(char(Key1{:}))," ","0000"),size(Key,1),size(Key,2));
results in a string array filing up all empty elements with "0000".
  댓글 수: 2
Sarah A
Sarah A 2020년 1월 19일
it is not working, I got this error:
Undefined function 'replace' for input arguments of type 'char'.
Walter Roberson
Walter Roberson 2020년 1월 19일
Which MATLAB version are you using? R2016a or earlier likely.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by