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

조회 수: 11 (최근 30일)
Chaudhary P Patel
Chaudhary P Patel 2022년 5월 10일
편집: dpb 2022년 5월 10일
i have ma=[a;b;0]
i want ma=[0;0;a+b]
please help me.
  댓글 수: 4
dpb
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
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
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.

카테고리

Help CenterFile Exchange에서 Source Control Integration에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by