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

1 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2021-3-7
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.

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2021-3-7
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.

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by