how can I add and change the position of elements in vector
4 次查看(过去 30 天)
显示 更早的评论
i have ma=[a;b;0]
i want ma=[0;0;a+b]
please help me.
4 个评论
dpb
2022-5-10
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
2022-5-10
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.
回答(1 个)
dpb
2022-5-10
编辑:dpb
2022-5-10
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Source Control Integration 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!