How to apply this formula into a matlab loop?

조회 수: 1 (최근 30일)
Lu Da Silva
Lu Da Silva 2022년 1월 25일
댓글: Esha Chakraborty 2022년 2월 1일
Hi, I have a table that looks like this:
% have: % wanted:
X Y Z
____________________________
A 1 2
B 2 2
C 3 -2
D 4 -2
A 5 2
B 6 2
C 7 -2
D 8 -2
A 9 2
B 10 2
C 11 -2
D 12 -2
I need to create a vector Z that only uses values when X=B or X=D and is solved as follows:
Z(1) = Y(4)-Y(2)
Z(2) = Y(4)-Y(2)
Z(3) = Y(4)-Y(6)
Z(4) = Y(4)-Y(6)
Z(5) = Y(8)-Y(6)
Z(6) = Y(8)-Y(6)
Z(7) = Y(8)-Y(10)
Z(8) = Y(8)-Y(10)
Z(9) = Y(12)-Y(10)
Z(10) = Y(12)-Y(10)
etc...
(note that the actual data has different numbers so it's not actually as easy as just creating a vector of 2s and -2s)
I'm struggling to implement this into matlab, e.g. in a loop... I hope someone can help me out!
Thanks

답변 (1개)

Esha Chakraborty
Esha Chakraborty 2022년 1월 28일
I understand that Z(i) = Y(b) - Y(a), where variables a and b are incremented by 4 after every 4 iterations. For this, you can use "rem" function inside "for" loop and iterate over the rows of the table. Then, embed the “if” statement inside to choose the values for subtraction.
Check the documentation for the "rem" here.
Use the below code for reference:
a = 0;
b = 2;
rows = 10;
for i = 1:rows %Can be modified as per requirements
if rem(i,4) == 3
b = b + 4;
end
if rem(i,4) == 1
a = a + 4;
end
Z(i) = Y(b) - Y(a);
disp(Z);
end
  댓글 수: 2
Lu Da Silva
Lu Da Silva 2022년 1월 31일
편집: Lu Da Silva 2022년 1월 31일
As I mentioned, the actual numbers are different, not 1,2,3.... Otherwise I would've just created a vector of -2 and 2. It is, however, the index of the number that is incremented by 4... So maybe it is possible to somehow modify your loop to fit that?
Esha Chakraborty
Esha Chakraborty 2022년 2월 1일
The code is only indexing for the values instead of using the values itself. Hence, it will work for any set of numbers other than what is provided. You can modify the initial variables and the increment as per requirements.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by