Putting NULLs in between the string array.

9 ビュー (過去 30 日間)
MakM
MakM 2022 年 3 月 30 日
コメント済み: MakM 2022 年 3 月 30 日
I have string array A={'a','b','c','d','e'}, and index vector index=[1,3,5]. I want to put NULL values at this location and shift other values. For example my output should be like this: Output={[],'a','b',[],'c','d',[],'e'}. How can I do that.

採用された回答

Simon Chan
Simon Chan 2022 年 3 月 30 日
Hope I understand it correctly, try this:
A={'a','b','c','d','e'};
index=[1,3,5];
newindex = index+(0:length(index)-1);
N = length(A)+length(index);
Output = repelem({''},1,N);
Output(~ismember(1:N,newindex))=A
Output = 1×8 cell array
{0×0 char} {'a'} {'b'} {0×0 char} {'c'} {'d'} {0×0 char} {'e'}
  4 件のコメント
Simon Chan
Simon Chan 2022 年 3 月 30 日
編集済み: Simon Chan 2022 年 3 月 30 日
May I know the definition of the index?
For the previous answer, I assume the empty cell happens before the 1st, 3rd and 5th letters.
Did your definition refers to the location of the empty positions like the following?
A={'a','b','c','d','e'};
index=[1,2,3,5];
N = length(A)+length(index);
Output = repelem({''},1,N);
Output(~ismember(1:N,index))=A
Output = 1×9 cell array
{0×0 char} {0×0 char} {0×0 char} {'a'} {0×0 char} {'b'} {'c'} {'d'} {'e'}
MakM
MakM 2022 年 3 月 30 日
Thanks for the answer. Yes this is what I exactly want :)

サインインしてコメントする。

その他の回答 (1 件)

Mathieu NOE
Mathieu NOE 2022 年 3 月 30 日
hello
here you are
A={'a','b','c','d','e'};
index=[1,3,5];
%% main code
ll = numel(A)+numel(index);
index_comp = (1:ll);
index2 = index + (0:numel(index)-1);
index_comp(index2) = [];
Output = cell(1,ll);
Output(index_comp) = A
  1 件のコメント
MakM
MakM 2022 年 3 月 30 日
Hey..
It is not working correct in the case if I want to put NULL on two consective values, for example if the index is [1,2,3,5], then not working correct.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by