Compare Strings in a loop

2 次查看(过去 30 天)
Kaan Aydin
Kaan Aydin 2020-8-15
评论: Kaan Aydin 2020-8-16
Hello everybody,
I have the followong question.
In a struct I have two cell arrays CellA and CellB. These cell arrays are identically built and contain the information "DataA, DataB, Name"
What I want to do ist to compare the strings of "Name" of both Cell arrays. If they are the same I want to calculate CellA.DataA - CellB.DataA
The calculated values are saved in a third cell array CellC. This is my actual script.
i=length(data.CellB);
a=1;
for k = 1:length(data.CellA)
while a < i
tf = strcmp(data.CellA{k, 1}.Reifen, data.CellB{a, 1}.Reifen);
if tf == 1
data.CellC{k,1} = data.CellA{k, 1}.DataA - data.CellB{a, 1}.DataA;
data.CellC{k,2} = data.CellA{k, 1}.DataA - data.CellB{a, 1}.DataA;
data.CellC{k,3} = data.CellA{k, 1}.DataB - data.CellB{a, 1}.DataB;
data.CellC{k,4} = data.CellA{k, 1}.DataB - data.CellB{a, 1}.DataB;
a=a+1;
else
data.Pegeldelta{k, 1}=0;
data.Pegeldelta{k, 2}=0;
data.Pegeldelta{k, 3}=0;
data.Pegeldelta{k, 4}=0;
end
end
end
But it seems like I´m stuck in an endless loop.
I think the problem is at "a". After the a=a+1 iteration it doesn´t get set back "a" so the loop doesn´t start again at 1 for the next comparison.
Hope you can help me with this.

采纳的回答

Rik
Rik 2020-8-15
If you know the number of interations, why not use a for loop again?
for k = 1:size(data.CellA,1) %use size(___,dim) instead of length() to get predictable behavior, use numel if you want all elements
A = data.CellA{k, 1}; %make the code more readable with a temp variable
for a = 1:size(data.CellB,1)
B = data.CellB{a, 1};
tf = strcmp(A.Reifen, B.Reifen);
if tf %don't compare a logical to 1
data.CellC{k,1} = A.DataA - B.DataA;
data.CellC{k,2} = A.DataA - B.DataA;
data.CellC{k,3} = A.DataB - B.DataB;
data.CellC{k,4} = A.DataB - B.DataB;
else
data.Pegeldelta{k, 1}=0;
data.Pegeldelta{k, 2}=0;
data.Pegeldelta{k, 3}=0;
data.Pegeldelta{k, 4}=0;
end
end
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Title 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by