How to apply this formula into a matlab loop?

2 views (last 30 days)
Hi, I have a table that looks like this:
% have: % wanted:
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)
(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!

Answers (1)

Esha Chakraborty
Esha Chakraborty on 28 Jan 2022
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;
if rem(i,4) == 1
a = a + 4;
Z(i) = Y(b) - Y(a);
Esha Chakraborty
Esha Chakraborty on 1 Feb 2022
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.

Sign in to comment.


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

Community Treasure Hunt

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

Start Hunting!