Hi everyone. I know it's a bit long, this should work with every kind of sorted vector. Feel free to refine it. Here it is:
%code A=[1 2 4 5]; % you must predefined a sorted vector. B=zeros(1,length(A)+1); L=length(A); n=input('ins num: ') for i=1:L for j=i:L if n>A(i) B(i+1)=n; B(i)=A(i); B(j+1)=A(j); elseif n==A(1) B(1:2)=A(1); B(i+1)=A(i); end end end B
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
10 Comments
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_101010
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_101010
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_101011
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_101011
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_101013
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_101013
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_271598
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_271598
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_271611
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_271611
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_271943
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_271943
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_271994
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_271994
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_529363
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_529363
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_529365
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_529365
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_529386
Direct link to this comment
https://in.mathworks.com/matlabcentral/answers/48942-insert-element-in-vector#comment_529386
Sign in to comment.