How to apply this formula into a matlab loop?
2 views (last 30 days)
Show older comments
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 Comments
Answers (1)
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.
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 Comments
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.
See Also
Categories
Find more on Whos 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!