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?
4 views (last 30 days)
Show older comments
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
Accepted Answer
Stephen23
on 31 May 2018
Edited: Stephen23
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
Stephen23
on 31 May 2018
Edited: Stephen23
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:
More Answers (0)
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!