Filter löschen
Filter löschen

Add a number(specific column) to vector without deleteing it.

2 Ansichten (letzte 30 Tage)
fyza affandi
fyza affandi am 29 Nov. 2018
Kommentiert: fyza affandi am 29 Nov. 2018
I have an vector
a= [1 2 3 4 5 6 7 8]
How can I add 2.5 into the vector a at any location( in this example I want it to be at column2)
so that the result will be:-
p/s: not replace , the length increases
a= [1 2.5 2 3 4 5 6 7 8]

Akzeptierte Antwort

KSSV
KSSV am 29 Nov. 2018
Bearbeitet: KSSV am 29 Nov. 2018
a= [1 2 3 4 5 6 7 8] ;
b = 2.5 ; % number to insert
pos = 2 ; % position at which number to be inserted
b = [a(1:pos-1) b a(pos:end)]

Weitere Antworten (2)

dpb
dpb am 29 Nov. 2018
One of many possible ways...
insertat=2;
val=2.5;
a=[a(1:insertat-1) val a(insertat:end)];
The key is to not store into the new array until the construction is done so don't change locations of expression RHS of assignment statement.

madhan ravi
madhan ravi am 29 Nov. 2018
Bearbeitet: madhan ravi am 29 Nov. 2018
Another possibility:
a=1:8;
b=zeros(1,numel(a)+1);
insert_position=2;
b(insert_position)=2.5;
b([1 insert_position+1:end])=a(:)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by