For loop to multiple columns

6 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by