Matrix function for subtracting and adding numbers from values in a matrix

I am trying to make a function that focuses on a matrix. I want the function to subtract 4 from any number in the matrix > 4, and then add 1 to each surrounding number in the matrix, until all numbers are < 4
If the matrix = [0 0 0;0 9 0; 0 0 0]
I want it to change to [0 2 0;2 1 2;0 2 0]

 採用された回答

Stephen23
Stephen23 2020 年 4 月 16 日
編集済み: Stephen23 2020 年 4 月 16 日
M = [0,0,0;0,9,0;0,0,0];
C = [0,1,0;1,-4,1;0,1,0];
while any(M(:)>4)
M = M + conv2(+(M>4),C,'same');
end

4 件のコメント

Carter Schultzen
Carter Schultzen 2020 年 4 月 16 日
That function only works once and changes the 9 to a 5 and adds 1, I need the function to repeat.
Stephen23
Stephen23 2020 年 4 月 16 日
編集済み: Stephen23 2020 年 4 月 16 日
"That function only works once and changes the 9 to a 5 and adds 1, I need the function to repeat. "
It repeats because of the while loop, this is the output:
>> M
M =
0 2 0
2 1 2
0 2 0
If your code is doing something else then please make a comment showing the exact and complete code that you are trying. I cannot debug your code if I cannot see it. Also make sure that you use the current answer (I simplified the code).
Carter Schultzen
Carter Schultzen 2020 年 4 月 16 日
This solution works for the numbers I proposed, but what could you do differently to make a function that changed worked for any number in the matrix being larger than 4. And then being able to add 1 to the surrounding numbers. Like say M = [0 0 0 0; 0 4 5 2; 0 1 1 0].
While any(M(l:j)>=4
M(l:j) - 4;
M(l-1:j) + 1;
M(l+1:j) + 1;
M(l:j-1) + 1;
M(l:j+1) + 1;
Or something along the lines of that, but I can't get it to work
Stephen23
Stephen23 2020 年 4 月 17 日
編集済み: Stephen23 2020 年 4 月 17 日
"This solution works for the numbers I proposed but what could you do differently to make a function that changed worked for any number in the matrix being larger than 4"
It already does:
>> M = [0 0 0 0; 0 4 5 2; 0 1 1 0]
M =
0 0 0 0
0 4 5 2
0 1 1 0
>> C = [0,1,0;1,-4,1;0,1,0];
>> while any(M(:)>4), M = M + conv2(+(M>4),C,'same'); end
>> M
M =
0 1 1 0
1 1 2 3
0 2 2 0
So far you have not actually given a specific example of when my code does not work as requested, nor explained why you think it does not work with "any number in the matrix being larger than 4" (even though it does, as shown above), nor have you explained why you think that it only "...works for the numbers I proposed".

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMathematics についてさらに検索

製品

タグ

質問済み:

2020 年 4 月 16 日

編集済み:

2020 年 4 月 17 日

Community Treasure Hunt

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

Start Hunting!

Translated by