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
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
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.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!