insert element in vector
Mostra commenti meno recenti
Hi everyone
now, how can I insert element in vector .... for example
a=[1,2,4,5]
how can I embed 3 between 2 and 4 in above vector to be
a=[1,2,3,4,5]
thank you
majid
11 Commenti
José-Luis
il 24 Set 2012
Is this homework?
Javier
il 24 Set 2012
As a member of a community we have to help to learn an not help to solve.
Like a lot José Luis comment.
Daniel Shub
il 24 Set 2012
What have your tried so far? Have you read any of the MATLAB documentation?
Jonathan Campelli
il 12 Mar 2015
The three comments above are disappointing to read, and I am glad that others made themselves available to answer the question the day it was asked.
@Jonathan: You find many questions here, which would be solved automatically if the asking persons read the documentation. You cannot use Matlab efficiently without reading the docs, at least the Getting Started chapters. Therefore comments like the ones above might be of deeper use, when they encourage the user to learn the basics instead of asking others to solve trivial problems.
We find too many homework questions here and posting a solution would decrease the learning effect.
Anyway, an interesting set of different solutions can be useful even if the question is trivial. Therefore I appreciate the answers here also. The OP wil learn something about anonymous functions, if he tries to understand Daniels solution - and this is more than he actually needs. Fine!
[EDITED, 28-Jan-2018 20:25 UTC] Concerning the flag of Sami Belhareth: You have flagged my comment as "rude and unnecessary". You misinterpret me completely. I explained Jonathan the background of the first three comments written by other members of the forum. I neither claimed that this is a homework question nor did I address the OP Majid at all, but talked to Jonathan. There is no rude term or sentence in my comment. I have posted only some very general facts concerning the communication in the forum. With which of the sentences of my comment do you disagree?
Your "This isn't a homework problem" is a speculation.
Jonathan Campelli
il 13 Mar 2015
Regarding your response, Jan,
You have made approximately 8,890 more contributions on MATLAB central than I have, and I’m certain I’ve run into your answers more than once (though I seem to run into Oleg’s more than anyone else’s) as I’ve combed through MATLAB Answers for countless methods for improving my code at the office. When I read recommendations to "read the documentation", I recall the mixed experience that I have doing just that. Some days I happily notice little details, like the use of negative integers within the column sorting vector in “sortrows” to indicate ‘descending’. Other days, my eyes are watering from combing through the Documentation for basic help, and I am glad when I find a great solution here on the Answers page that gives me some new functions to look up or some new techniques to employ.
Sometimes my questions (after all my searching) are as simple as Majid’s, and that makes me hesitant to assume that his question has arisen from poor effort (or that it's even a HW question, even though I've looked through his other questions). Majid did not disclose how much time he had put into it and what efforts he already made. I do not take the position of one who deems it important to ask, but I do want to eventually be a helpful resource on MATLAB Central, if that means changing my stance. What are your thoughts?
Jan
il 14 Mar 2015
Modificato: John Kelly
il 10 Nov 2017
@Jonathan: I like your positiv point of view. It is a pleasure to read it.
We find a lot of homework questions in the forum. Some users are impolite and offending, some post spam to earn money with disturbing engaged people, while they help others voluntarily. Some very ative contributors have left the forum due to frustration. As long as I did include my email address in my profile, I received homework questions by email, up to 10 per week. Some of them contained phrases like "solve my problem soon, it is urgent" and most of them did not show any own effort.
Majid did not write a comment and did not take the time to accept an answer to mark the question as solved. He took the time to formulate the question clearly and with all required details and said "thank you" in advance.
Finally I think, you are right. Some of the users do not show enough respect for the time and energy spent by the ones who write answers. Some contributors struggle with frustration instead of answering only, when they feel free and happy to do so. But the vast majority of threads is efficient, polite, useful. This forum needs persons, who want to be a helpful resource.
Walter Roberson
il 28 Gen 2018
Sami Belhareth commented to Jan Simon:
This isn't a homework problem, they are looking for how to do a specific thing that may or may not be difficult to find in the documentation due to its specificity. Rude and unnecessary comment
Walter Roberson
il 28 Gen 2018
Sami Belhareth:
Back in September 2012 when Majid Al-Sirafi asked the question, Majid was a student asking student questions. At the time we responded, we knew that from previous interactions. There was a significant chance that it was indeed a homework related question. People were justified in asking whether it was homework or not, as we answer differently if it is: for homework we explain a lot more and teach the student how to think about questions to increase their understanding of the language and of programming in general, where-as for non-homework we are more likely to give short code under the assumption that the person already understands MATLAB and programming.
Jan
il 29 Gen 2018
@Walter: Thanks for your comment concerning homework. I think Sami's point is more my "rudeness".
The admins had cleaned up this thread in Nov-2017 already. I think it is strange, that the first activity from Sami's account is flagging a 3 year old comment in a 6 year old thread as being rude.
Luck Haviland
il 8 Dic 2022
Not sure if I am breaking the matlab forums code of conduct by not answering OP's question but I agree with @Jonathan Campelli's way of looking at answering peoples questions. Even if the question is a homework question for one person, it can be a non homework question for another person. If the question is never answered, there will be no learning which defeats the purpose of a community forum.
Risposta accettata
Più risposte (6)
Jonathan Campelli
il 12 Mar 2015
16 voti
Here is an application specific solution:
a=[1 2 4 5] %Your predefined vector.
a=sort([a 3]) %The "[a 3]" operation adds the element 3 to the end of vector "a", creating vector [1 2 4 5 3]. "Sort()" then alligns the new vector's elements in order from least to greatest.
4 Commenti
Maximilian Sgodda
il 7 Ago 2020
Thanks Jonathan!
I had a slightly different problem, like the question was asked and could solve it with your code :)
Koosha
il 31 Gen 2022
Thank you soooooo much.
Dana Massie
il 21 Giu 2022
love it. so simple. Thanks.
Jack
il 7 Feb 2024
Thanks man!
Daniel Shub
il 24 Set 2012
While I think this is a homework problem ...
Function handles and cat are your friends
insert = @(a, x, n)cat(2, x(1:n), a, x(n+1:end));
insert(3, [1,2,4,5], 2)
ans = 1 2 3 4 5
Andrei Bobrov
il 24 Set 2012
Modificato: Andrei Bobrov
il 24 Set 2012
b = 3;
i1 = 3;
a = [a(1:i1-1),b,a(i1:end)];
or
a = [1 2 4 5];
i1 = 3;
b = 3000;
n = numel(b);
out = ones(size(a) + [0 n]);
out(i1 + (0:n-1)) = 0;
out(out > 0) = a;
out(out == 0) = b;
1 Commento
Bernard
il 29 Lug 2019
a = [1 2 4 5];
b = 3;
idx = 3;
a = [a(1:length(a) < idx), b, a(1:length(a) >= idx)];
Simpler version of your second example, which I prefer because it works with idx == 1 or idx == length(a).
JMP Phillips
il 20 Apr 2021
Modificato: DGM
il 4 Mar 2023
If you are reading this in 2021 now in MATLAB you can just do something like this (no for loops, no 'cat'). It can also work with inserting more than 1 element into a vector.
y = zeros(1,length(x)+length(b)); %initialise a new vector of the appropriate size
y(a) = b; %insert the values in 'b' at the locations in 'a'
y(y==0) = x; %insert the original values in x into the new vector at their new positions.
where
- x is the existing vector to insert values into
- a is vector of indices where to put new values
- b is vector of new values
NOTE: because we use 0 we cannot insert a value of 0, this works for non-zero values only.
Example with inserting multiple values at specified locations into an array:
x = [1,2,3,4,5]
a = [3,5,1,4]
b = [5, nan, 3, 717]
Result:
y = 3 1 5 717 NaN 2 3 4 5
and the original question with inserting 1 element would be solved by
x = [1,2,4,5]
a = 3
b = 3
Result:
y = 1 2 3 4 5
1 Commento
Pol Cardona Rubio
il 15 Apr 2024
Modificato: Pol Cardona Rubio
il 15 Apr 2024
If instead of creating it with a zero value you create it with NaN and then index based on isnan() it can be used with any valued vector as in:
y = repmat(NaN,length(x)+length(b)); %initialise a new vector of the appropriate size
y(a) = b; %insert the values in 'b' at the locations in 'a'
y(isnan(y)) = x; %insert the original values in x into the new vector at their new positions.
Walter Roberson
il 7 Mar 2018
2 voti
There is no MATLAB operator for inserting into a MATLAB vector. Concatenating elements as described by Wayne King, Andrei Bobrov, and Daniel Shub is the natural MATLAB solution to this task.
The only exception to this is MATLAB String objects (R2016b and later), which have insertBefore and insertAfter operations defined for them that search the input strings to match a given text and insert at that point.
I have attached code to implement insertion after a given point into generalized vectors. Generalized vectors here refers to the fact that the vectors might have 3 or more dimensions, and that the code is not restricted to numeric or char.
There are some important differences between this code and the ones posted above:
- this code handles vectors of any dimension, not just row vectors
- the output is the same class as the initial vector even if different data types are involved. For example the other implementations if asked to insert 'a' after (double) 50 would produce '2a' because [50 'a'] automatically converts the double to char because of MATLAB rules about converting to the most restrictive data type when cat() is used. The code I attached will produce [50 97] instead -- but if you ask to insert (double) 50 before 'a' then you will get '2a' because the data type of the original vector is retained
- However, an empty original array will cause the output to be in the type of the new data so that you can always use [] to indicate empty array no matter what type you are appending
There are a number of design decisions explicitly documented in the code -- this seemingly simple operation is surprisingly complex.
1 Commento
Manuel Infante Francés
il 5 Apr 2023
Modificato: Manuel Infante Francés
il 5 Apr 2023
Good morning, I have the following problem, in the thread of this forum:
I am trying to add an element to a column vector (B1 of m rows) that is the output of a Matlab Function block. The output vector (B) is desired to have m+1 rows. When adding the element (with value = x), the resulting output (B) is a vector of m+1 rows, with the particularity that all the rows will acquire the value (x) of the added element. Add the value you add and use the method you use (cat function, indexing etc.), the resulting vector is effectively a vector of m+1 elements, but with the same value (x) for all its elements.
Example:
function B=fcn(A,Ts)
B1 =diff(A)/Ts;
B =[1;B1];
In the example below, 1 is the value I want to index into B1 to get B. A has 501 elements and I want the output of function (B) to also have 501 elements (the value of the first row element must be 1 and from row 2 to the last one -both included- it should be the vector B1). However, all the elements of B are equal to 1. Ts comes from a constant block with scalar value (0.02).
Thank you.
Elena Fiermonte
il 30 Set 2018
Modificato: DGM
il 4 Mar 2023
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
Categorie
Scopri di più su Get Started with MuPAD in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!