How to apply this formula into a matlab loop?
조회 수: 1 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (1개)
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.
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
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 Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!