Creating a For Loop to Compare Every Two Cells in Array

8 次查看(过去 30 天)
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