For loop to multiple columns

조회 수: 4 (최근 30일)
david crowley
david crowley 2021년 4월 27일
답변: Arjun 2025년 3월 4일
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?

답변 (1개)

Arjun
Arjun 2025년 3월 4일
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!

카테고리

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