how can I add and change the position of elements in vector
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
i have ma=[a;b;0]
i want ma=[0;0;a+b]
please help me.
4 commentaires
dpb
le 10 Mai 2022
Did you try it????
>> ma=[2;3;0];
>> ma=[repmat(ma(3),2,1); sum(ma(1:2))]
ma =
0
0
5
>>
meets the expectation given.
dpb
le 10 Mai 2022
Unless you're meaning what you didn't say/write that you don't actually have ma but want it from the elements a,b instead. That would simply be
ma=[zeros(2,1);a+b];
as one way; there are any number of ways to write an equivalent expression.
It simply isn't clear what your problem context is in order to have any better ideas of what might be a more general solution to the (unstated) problem.
Réponses (1)
dpb
le 10 Mai 2022
Modifié(e) : dpb
le 10 Mai 2022
NB: even if you have (again the unstated problem)
>> a=2;b=3;
>> ma=[a;b;0];
>> ma=[repmat(ma(3),2,1); sum(ma(1:2))]
ma =
0
0
5
>>
the above solution works from the base definition of ma with the components a, b.
Of course, if you replace ma with the new version by executing the last line a second time, the result will then be some new matrix with different characteristics; it's operation-order dependent when you do that. If you must preserve the original ma, then you'll have to create mb instead of overwriting ma as you've illustrated so far. IOW, you MUST keep the code snippet above together if the result is to be as expected.
The key thing here is that MATLAB evaluates the RHS of an assignment statement in its entirety with values of all variables in context at the time of execution of the given assignment statement, including the present content of whatever is the LHS variable (if referenced as is here, of course). Hence, all the elements of ma are those at the end of the previously executed statement and are not affected by anything done on the RHS until they completely replace the previous assignment. Any assignment to a variable on the LHS without explicit indexing completely clears and replaces the entire variable as if it had never existed up to that time.
0 commentaires
Voir également
Catégories
En savoir plus sur Source Control Integration dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!