Creating a For Loop to Compare Every Two Cells in Array

8 views (last 30 days)
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 Comment
Walter Roberson
Walter Roberson on 5 Oct 2023
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)

Sign in to comment.

Answers (1)

Fabio Freschi
Fabio Freschi on 5 Oct 2023
Edited: Fabio Freschi on 5 Oct 2023
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"

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!