MATLAB Answers

I have a cell array of 1 x 8 size.I want to add a zero in between two cells.How do i do this in matlab?

1 view (last 30 days)
In MATLAB,I have a 1 x 8 cell array.The numbers are
-4.5,-1.5 ,-2.5,-1.2,1.2,2.5,1.5,4.5
I iterate through the whole cell.I take absolute values of each element.As soon as i encounter equal elements (Here it is going to be 1.2 and 1.2), i add a zero in between them. Overall it becomes a 1 x 9 cell array.Kindly help me with this.

  0 Comments

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 31 May 2018
Edited: Stephen Cobeldick on 31 May 2018
>> V = [-4.5,-1.5 ,-2.5,-1.2,1.2,2.5,1.5,4.5];
>> Z = V;
>> Z(2,:) = 0;
>> Z = Z([true(size(V));~diff(abs(V)),false]).'
Z =
-4.50000 -1.50000 -2.50000 -1.20000 0.00000 1.20000 2.50000 1.50000 4.50000

  2 Comments

sachin narain
sachin narain on 31 May 2018
Thank you.This worked. Can you tell explain the logic of the code please. And what if i have numbers like :
0.15, 0.15, 0, 0 ,0 ,0 ,0.15 ,0.15
and i want to add 0 exactly in between so that it then becomes a 1 x 9 cell array.
it wil be of great help
Stephen Cobeldick
Stephen Cobeldick on 31 May 2018
[0.15, 0.15, 0, 0 ,0 ,0 ,0.15 ,0.15]
The vector has 8 elements, but has two pairs or adjacent identical non-zero values, so why is the output not sized 1x10 ?
If 1x10 is actually the correct size, then this would do what you want:
>> V = [0.15, 0.15, 0, 0 ,0 ,0 ,0.15 ,0.15];
>> Z = V;
>> Z(2,:) = 0;
>> X = [~diff(abs(V)),false] & V~=0;
>> Z = Z([true(size(V));X]).'
Z =
0.15000 0.00000 0.15000 0.00000 0.00000 0.00000 0.00000 0.15000 0.00000 0.15000
This gives Z with 10 elements. If you really want 9 elements, then you will have to explain the logic to me, of why one pair does NOT require a zero to be inserted (and which pair).
PS: these are not cell arrays, these are numeric arrays. Numeric arrays do not have cells, they have elements You can read about the different basic data classes here:

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Tags