Replace cell contents using an if statement nested inside a for loop?
1 view (last 30 days)
Show older comments
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 Comment
Stephen23
on 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.
Answers (1)
Walter Roberson
on 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.
0 Comments
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!