Is there a quick and easy way to insert/delete values into the middle or beginning of a cell array and/or a numerical array

I have a cell array and a numerical array. I want to insert values into the beggining, middle and end of the cell array or the numerical array. Is there an easy way to do this.
I also want to be able to delete array elements at the beginning, middle or end of the arrays. Same question...

 Réponse acceptée

Just use indexing:
>> V = randperm(9)
V =
9 5 7 3 4 6 8 2 1
>> idx = 3;
>> val = 0;
>> V = [V(1:idx),val,V(idx+1:end)]
V =
9 5 7 0 3 4 6 8 2 1
Note that this will work for the beginning and end too (try it with idx=0).

Plus de réponses (1)

a=1:11;
a(1) = somevalue%first element [] square bracket removes that element
a(fix(mean(a))) %mid element
a(end) % last element

4 commentaires

Hi Thanks for your answer but I don't think it works for me. I want to be able to INSERT values into the array/cell. If there are 11 (a=1:11;) elements in the array and I insert one after index location 5 the array will now have 12 elements and a new element 6. Not 11 with a new value at location 5. If I delete an element 6 instead of 11 elements in the array it will have 10 elements with element 6 gone. So I want to be able to insert elements anywhere in the array increasing the size of the array by 1 each time I insert. I also want to be able to delete specific elements in the array/cell reducing the size of the array by 1 each time I delete an element. Thanks
I am having trouble understanding you please give an example.
say we have a 4 element array where
a(1) has value 1
a(2) has value 2
a(3) has value 3
a(4) has value 4
I want to be able to insert a new value in a new location anywhere in the array.
Say I want to insert the value 6 after the second element of the array. The new array would look like (note it now has 5 elements):
a(1) would have value 1
a(2) would have value 2
a(3) would have value 6
a(4) would have value 3
a(5) would have value 4
If i then wanted to delete the second element the new array would then have 4 elements again.
a(1) would have value 1
a(2) would have value 6
a(3) would have value 3
a(4) would have value 4
The array would grow and shrink as i inserted and deleted elements. I know I can do this with multiple arrays. The question is, is there an easier way to do it using MATLAB Functions/abilities.
Thanks
Bob
"is there an easier way to do it using MATLAB Functions/abilities."
Not really. Indexing is the easiest way.

Connectez-vous pour commenter.

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by