# For loop to carry value down depending on another matrix value

조회 수: 2(최근 30일)
IDN 2022년 2월 22일
댓글: IDN 2022년 2월 22일
Hello!
I have the following issue. I have 2 matrices (MatrixA and MatrixB), I want to create a third one(MatrixC) that uses the information on both as follows:
MatrixA MatrixB MatrixC
_______ _______ ______
0 150 0
0 1100 0
0 50 0
-1 20 0 When MatrixA switches from 0 to -1 use MatrixB Value,
-1 120 20 and copy that value all the way down until MatrixA
-1 70 20 turn to 1 and then repeat for every other instance
-1 90 20 very likely a for loop way.
1 100 20
0 101 0
-1 115 0
-1 110 115
-1 160 115
-1 200 115
-1 275 115
-1 400 115
-1 500 115
1 504 115
Preferably MatrixC maintains same size as MatixA OR MatrixC that’s why the zeros filling the gaps when it’s not applicable. Thanks so much for the help!

댓글을 달려면 로그인하십시오.

### 채택된 답변

J. Alex Lee 2022년 2월 22일
In your example, there is a "delay" by 1 row when your switch from 0 to -1 occurs, so the following answer is not exactly producing the example, but maybe it can get you started
data = array2table([ 0 150
0 1100
0 50
-1 20
-1 120
-1 70
-1 90
1 100
0 101
-1 115
-1 110
-1 160
-1 200
-1 275
-1 400
-1 500
1 504],"VariableNames",["A","B"])
data = 17×2 table
A B __ ____ 0 150 0 1100 0 50 -1 20 -1 120 -1 70 -1 90 1 100 0 101 -1 115 -1 110 -1 160 -1 200 -1 275 -1 400 -1 500
data.C = nan(height(data),1);
% find where A switches from -1 to 0
sw = [false;diff(data.A)==-1]
sw = 17×1 logical array
0 0 0 1 0 0 0 0 1 1
% copy B into C when switch condition is met
data.C(sw) = data.B(sw)
data = 17×3 table
A B C __ ____ ___ 0 150 NaN 0 1100 NaN 0 50 NaN -1 20 20 -1 120 NaN -1 70 NaN -1 90 NaN 1 100 NaN 0 101 101 -1 115 115 -1 110 NaN -1 160 NaN -1 200 NaN -1 275 NaN -1 400 NaN -1 500 NaN
% fix C to 0 when A=0
data.C(data.A==0) = 0
data = 17×3 table
A B C __ ____ ___ 0 150 0 0 1100 0 0 50 0 -1 20 20 -1 120 NaN -1 70 NaN -1 90 NaN 1 100 NaN 0 101 0 -1 115 115 -1 110 NaN -1 160 NaN -1 200 NaN -1 275 NaN -1 400 NaN -1 500 NaN
% fillmissing with previous value
data.C = fillmissing(data.C,"previous")
data = 17×3 table
A B C __ ____ ___ 0 150 0 0 1100 0 0 50 0 -1 20 20 -1 120 20 -1 70 20 -1 90 20 1 100 20 0 101 0 -1 115 115 -1 110 115 -1 160 115 -1 200 115 -1 275 115 -1 400 115 -1 500 115
IDN 2022년 2월 22일
Thanks!

댓글을 달려면 로그인하십시오.

### 범주

Find more on Loops and Conditional Statements in Help Center and File Exchange

R2020a

### Community Treasure Hunt

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

Start Hunting!

Translated by