how can I add and change the position of elements in vector

i have ma=[a;b;0]
i want ma=[0;0;a+b]
please help me.

4 Comments

Not much to be done there than to just write it out...any number of possible ways, but using existing elements only one choice could be
ma=[repmat(ma(3),2,1); sum(ma(1:2))];
There's really nothing all that satisfying that could be done here that can see...there must be more to the Q? than appears here???
@dpb sir, i do not think it will work for what i am expecting.
suppose
a=2;
b=3
so ma=[2;3;0]
i want out put as a [0;0;5].
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.
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.

Sign in to comment.

Answers (1)

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.

Products

Asked:

on 10 May 2022

Edited:

dpb
on 10 May 2022

Community Treasure Hunt

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

Start Hunting!