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

1 回表示 (過去 30 日間)
Alaa Al-Saffar
Alaa Al-Saffar 2017 年 5 月 20 日
コメント済み: Alaa Al-Saffar 2017 年 5 月 20 日
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

採用された回答

the cyclist
the cyclist 2017 年 5 月 20 日
編集済み: the cyclist 2017 年 5 月 20 日
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
  1 件のコメント
Alaa Al-Saffar
Alaa Al-Saffar 2017 年 5 月 20 日
Thank you very much,
You solution works perfectly!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by