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

1 view (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 9 Feb 2022
Edited: Stephen23 on 9 Feb 2022
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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!