For loop to multiple columns
2 views (last 30 days)
Show older comments
I have the following block of code:
%RSI Calculation
n = [14:2:18];
for i = 1:n
gainC = diff(ABC).*((diff(ABC))> 0);
lossC = -(diff(ABC)).*((diff(ABC)) < 0);
avg_gainC = movmean(gainC,[i-1 0],'omitnan');
avg_lossC = movmean(lossC,[i-1 0],'omitnan');
RS = (avg_gainC ./ avg_lossC);
ABC_RSI = 100 - (100 ./ (1+RS));
end
I need to know how I can create a table 'ABC_RSI' with the columns 14w_RSI, 16w_RSI, 18w_RSI and populated using the formula. Can someone please help?
0 Comments
Answers (1)
Arjun
on 4 Mar 2025 at 6:34
I see that the goal is to compute the '14w_RSI', '16w_RSI', and '18w_RSI' values within a loop and store each set of computed RSI values in separate columns of a table.
This can be done by creating a table in MATLAB using 'table' function and then modifying the 'for' loop to log entries in the table before the next iteration begins. Kindly refer to the modified code below:
% Initialize an empty table for ABC_RSI
ABC_RSI_Table = table();
% RSI Calculation
n = 14:2:18;
for idx = 1:length(n)
i = n(idx);
gainC = diff(ABC).*((diff(ABC)) > 0);
lossC = -(diff(ABC)).*((diff(ABC)) < 0);
avg_gainC = movmean(gainC,[i-1 0],'omitnan');
avg_lossC = movmean(lossC,[i-1 0],'omitnan');
RS = (avg_gainC ./ avg_lossC);
ABC_RSI = 100 - (100 ./ (1 + RS));
% Create a variable name for the current RSI period
varName = sprintf('%dw_RSI', i);
% Add the value as a new column
ABC_RSI_Table.(varName) = ABC_RSI;
end
disp(ABC_RSI_Table);
Kindly refer to the documentation of the 'table' function of MATLAB: https://www.mathworks.com/help/releases/R2021a/matlab/ref/table.html
I hope this helps!
0 Comments
See Also
Categories
Find more on Logical 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!