Creating a For Loop to Compare Every Two Cells in Array

8 Ansichten (letzte 30 Tage)
oronir
oronir am 5 Okt. 2023
Kommentiert: Walter Roberson am 5 Okt. 2023
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 Kommentar
Walter Roberson
Walter Roberson am 5 Okt. 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)

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Fabio Freschi
Fabio Freschi am 5 Okt. 2023
Bearbeitet: Fabio Freschi am 5 Okt. 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"

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by