Effacer les filtres
Effacer les filtres

Replace cell contents using an if statement nested inside a for loop?

1 vue (au cours des 30 derniers jours)
Owen Gray
Owen Gray le 7 Mar 2021
Commenté : Stephen23 le 7 Mar 2021
I'm trying to run this change the contents of an 81698x10 cell array 'A'
[sizeA,rows] = size(A);
clear rows
for n = 1:sizeA
if A{n,8} == 'simulated' && A{n,4} == 1
A{n,9} = A{n,9} + 60;
end
end
however when I try and run I get an error message-
Matrix dimensions must agree
Would greatly appreciate help with this! Thanks
  1 commentaire
Stephen23
Stephen23 le 7 Mar 2021
Do not use == to compare strings, instead use strcmp or strcmpi. Replace
A{n,8} == 'simulated' % element-wise, unlikely to be useful for your situation.
with
strcmp(A{n,8},'simulated') % does what you want.

Connectez-vous pour commenter.

Réponses (1)

Walter Roberson
Walter Roberson le 7 Mar 2021
sizeA = size(A, 1);
for n = 1:sizeA
if strcmp(A{n,8}, 'simulated') && A{n,4} == 1
A{n,9} = A{n,9} + 60;
end
end
Reminder though that comparing character vectors is more expensive than comparing numbers so it might make sense to compare the number first.
A tip is that when you are using the && operator, that it can make sense to put the comparisons most likely to be false first, to fail with as little average work as practical. Likewise when using it can make sense to put the likely truths first to succeed with as little average work as possible. However, over the lifetime of a program, it is usually better to write clear code rather than worrying too much about optimization.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by