Creating a For Loop to Compare Every Two Cells in Array

조회 수: 4 (최근 30일)
oronir
oronir 2023년 10월 5일
댓글: Walter Roberson 2023년 10월 5일
Hi All,
I want to create a loop that compares every two values in an array.
For example:
HD_Affect = ["Neutral" "Positive" "Negative" "Positive" "Neutral" "Negative"]
if "Neutral" then "Positive" || "Negative" then "Positive"
Res = "Positive";
elseif "Neutral" then "Negative" || "Positive" then "Negative"
Res = "Negative";
elseif "Positive" then "Positive" || "Neutral" then "Neutral" || "Negative" then "Negative"
Res = "Same";
else
Res = "NaN";
end
I want to be able to compare 1 and 2, 3 and 4, 5 and 6, and so on.
I would then want each of these results put into the variable Res where I could then use summary(Res) or another way to identify the number of times each of these (Positive, negative, same) happens.
Does anyone know if there is a way to set up a For loop that would compare every 2 elements in the array using the If statements outlined and combine the answers into a separate array? I hope this isn't two confusing and would appreciate any help I could get. Thank you!
  댓글 수: 1
Walter Roberson
Walter Roberson 2023년 10월 5일
Does it need to be a for loop? Because you can simplify the code by using a 2D array, including with using categorical as indices.
%for example after having constructed appropriate categoricals,
Results(Neutral,Positive) = Positive;
Results(Negative,Positive) = Positive;
%and later
Res = Results(FirstInput, SecondInput)

댓글을 달려면 로그인하십시오.

답변 (1개)

Fabio Freschi
Fabio Freschi 2023년 10월 5일
편집: Fabio Freschi 2023년 10월 5일
I try to translate your pseudocode into Matlab instructions
HD_Affect = ["Neutral" "Positive" "Negative" "Positive" "Neutral" "Negative"];
% preallocation
Res = strings(1,length(HD_Affect)/2);
% loop
for i = 1:2:length(HD_Affect)
if strcmpi(HD_Affect(i),"Neutral") & strcmpi(HD_Affect(i+1),"Positive") ...
|| strcmpi(HD_Affect(i),"Negative") & strcmpi(HD_Affect(i+1),"Positive")
Res((i+1)/2) = "Positive";
elseif strcmpi(HD_Affect(i),"Neutral") & strcmpi(HD_Affect(i+1),"Negative") ...
|| strcmpi(HD_Affect(i),"Positive") & strcmpi(HD_Affect(i+1),"Negative")
Res((i+1)/2) = "Negative";
elseif strcmpi(HD_Affect(i),"Positive") & strcmpi(HD_Affect(i+1),"Positive") ...
|| strcmpi(HD_Affect(i),"Neutral") & strcmpi(HD_Affect(i+1),"Neutral") ...
|| strcmpi(HD_Affect(i),"Negative") & strcmpi(HD_Affect(i+1),"Negative")
Res((i+1)/2) = "Same";
else
Res((i+1)/2) = "NaN";
end
end
disp(Res)
"Positive" "Positive" "Negative"

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by