0

I have a cell array of strings (length = 4):
A = {'a', 'b', 'c', 'd'}
I have a double matrix of indices (length = 4):
B = [2, 4, 6, 8]

How can I create a new cell array C (of strings) of length = 8, that uses the indices in B to place the strings from A into the new array C. For any index not specified in B, I want to enter a ' ' space (empty string). Note: my real data does not go "every-other".

C = {' ', 'a', ' ', 'b', ' ', 'c', ' ', 'd'}

How can this be done in Matlab?

4
  • how did you come with 8? Is it 4+4, or is it the maximum index in B? Commented Oct 31, 2014 at 1:04
  • No, the lengths of A, B, and C were arbitrary, except that the lengths of A and B need to be equal (because the indices in B correspond to the strings in A). Commented Oct 31, 2014 at 1:12
  • what I meant was, what if B was B=[100 200 300 400]? Commented Oct 31, 2014 at 1:13
  • Yes, the values of B could be [100, 200, 300, 400], but then my new cell array C would need to be at least length = 400 or greater. Commented Oct 31, 2014 at 1:14

2 Answers 2

2

This is another approach, very similar to the above, but no repmat.

C(B)=A;
C(cellfun('isempty',C))={' '}; 

I have replaced traditional @isempty since it may be faster. Thanks @LuisMendo for mentioning that in a comment.

Sign up to request clarification or add additional context in comments.

1 Comment

C(cellfun('isempty',C)) may be faster than C(cellfun(@isempty,C))
1

One possible approach:

C = repmat({' '}, 1, max(B)); %// predefine with ' ';
C(B) = A; %// replace actual values

Or:

C(B) = A; %// this automatically fills missing values with [] 
ind = cellfun('isempty', C); %// find occurrences of [] 
C(ind) = repmat({' '}, 1, sum(ind)); %// replace them with ' '

The last line could be simplified as follows (no repmat needed), as noted by @ParagS.Chandakkar:

C(ind) = {' '}; %// replace them with ' '

1 Comment

Great, thanks! I would only add this step before your code, to create the empty cell array C = repmat({''},1,8);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.