Creating a For Loop to Compare Every Two Cells in Array

7 ビュー (過去 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 Center および File ExchangeMatrices and Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by