Add a Number to a Certain elements and the elements that follows

1 Ansicht (letzte 30 Tage)
Hello,
Suppose I have two Matrices A & B
>> A=[1 2 5;7 11 12;15 17 19]
A =
1 2 5
7 11 12
15 17 19
>> B=[2 4 6;10 12 14;16 19 22]
B =
2 4 6
10 12 14
16 19 22
I have a variable say (c) that I will obtain it's value from other commands and used it to find which element in matrix A that equal to it's value.
for example c=2
This means I have to locate the element in Matrix A that =2, which is A(1,2).
Then I want to add a number say (Num=1) to original value of A(1,2) and the elements that follows this elements (i.e. from A(1,3) to A(3,3)), Also I want to add the same number to Matrix B for the elements from B(1,3) to B(3,3), without B(1,2).
How to that?
The Expected Result are:
A =
1 3 6
8 12 13
16 18 20
B =
2 4 7
11 13 15
17 20 23
I am thinking of something like this, but it is totally not correct
A(find(A==c))=Original_Value+Num
B(find(A==c))=Original_Value+Num %Stating from B(1,3) not from B(1,2) as A
Thank you in-advance
Alaa

Akzeptierte Antwort

the cyclist
the cyclist am 20 Mai 2017
Bearbeitet: the cyclist am 20 Mai 2017
It's easiest to do this using linear indexing. There is a slight complication in that you want to "index along rows", but linear indexing works down along columns. But, it is still pretty straightforward:
A = [1 2 5;7 11 12;15 17 19];
B = [2 4 6;10 12 14;16 19 22];
c = 2;
Num = 1;
At = A'; % Use the transpose of A, because linear indexing is columnwise.
Bt = B'; % Ditto
idx = find(At==c);
At(idx:end) = At(idx:end) + Num;
Bt(idx+1:end) = Bt(idx+1:end) + Num;
A = At'; % Transpose back
B = Bt'; % Ditto

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by