For Loop that Checks 2 Matrices to create a Combined New one based on IF Statement

2 次查看(过去 30 天)
Good Morning,
I have the following statement that check 3 data sets to combine an answer (1,0,-1) but i am not able to get it to work. I am new in MATLAB and i am able to get an excel statement that works (attached in file).
sOpen = zeros(size(sOpen));
sClose = zeros(size(sOpen));
sCombined = zeros(size(sOpen));
for k = 2:numel(sOpen)
kk = sOpen(k)~=0 && sClose(k)~=0; % To check if there is a value -1 or 1 in sOpen and sClose
if all(kk)
kkk = sCombined(k-1)==-1 & sClose(k) ==1; % If prior combined result equals -1 and current CLOSE = 1 then result = 1
sCombined(k) = 1;
elseif all(~kkk)
kkkk = sCombined(k-1)==0 & sOpen(k) ==-1; % If prior combined result equals 0 and current OPEN = -1 then result = -1
sCombined(k) = -1;
elseif all(~kkk)
kkkkk = sCombined(k-1)==-1 & sClose(k) ==0; % If prior combined result equals -1 and current CLOSE = 0 then result = -1
sCombined(k) = -1;
else
sCombined(k) = 0; %Anything else should be 0
end
end

采纳的回答

Stephen23
Stephen23 2022-2-9
编辑:Stephen23 2022-2-9
Here is a direct translation of your Excel formula:
T = readtable('Data.xlsx') % import your data
Warning: Column headers from the file were modified to make them valid MATLAB identifiers before creating variable names for the table. The original column headers are saved in the VariableDescriptions property.
Set 'VariableNamingRule' to 'preserve' to use the original column headers as table variable names.
T = 4252×5 table
Sopen Sclose CurrentStatement CorrectAnswer ExcelStatement _____ ______ ________________ _____________ ______________ 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
nmr = height(T);
out = zeros(nmr,1);
for k = 2:nmr
% IF(AND(E1=-1,B2=1),1,IF(AND(E1=0,A2=-1),-1,IF(AND(E1=-1,B2=0),-1,0)))
if out(k-1)==-1 && T.Sclose(k)==1
out(k) = 1;
elseif out(k-1)==0 && T.Sopen(k)==-1
out(k) = -1;
elseif out(k-1)==-1 && T.Sclose(k)==0
out(k) = -1;
end
end
isequal(out,T.CorrectAnswer)
ans = logical
1
isequal(out,T.ExcelStatement)
ans = logical
1

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by