Arrays have incompatible sizes for this operation.
2 次查看(过去 30 天)
显示 更早的评论
OptSelection = input(' Will you like to Add Delete ','s');
while strcmpi(OptSelection,"Add") ~=1 && strcmp(OptSelection,"Delete") ~=1
fprintf(' You have selected a not existing option \n');
fprintf(' Make sure that the initials of the selected option are capital \n');
OptSelection = input(' Selected the correct option ','s');
end
fprintf('Print %s \n',OptSelection);
if OptSelection == 'Delete'
fprintf('Okay1');
else OptSelection == 'Add';
fprintf('Okay2');
end
0 个评论
采纳的回答
Walter Roberson
2023-3-12
while strcmpi(OptSelection,"Add") ~=1 && strcmp(OptSelection,"Delete") ~=1
That is valid code, if a bit awkward. Less awkward would be something like
while ~ismember(lower(OptSeletion), ["add", "delete"])
then
if OptSelection == 'Delete'
Earlier you used "Delete" instead of 'Delete' and you used strcmpi() instead of == . The previous test was valid. But this test is comparing the character vector in OptSelection to the character vector 'Delete'. This is like coding if [65 100 100] == [68 101 108 101 116 101] -- you know it is going to error out because the two vectors are not the same length.
When you are comparing character vectors use strcmp() or strcmpi() .
Note that "Delete" is not a character vector, it is a scalar string() object. The == operation is defined for string objects and automatically takes different lengths into account; furthermore if you have a character vector == a string object, the character vector is automatically converted to a string object. So it would be valid to code
if OptSelection == "Delete"
... or you can use strcmp() or strcmpi()
Note that
fprintf(' Make sure that the initials of the selected option are capital \n');
the restriction to capitals is not necessary if you use strcmpi()
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Dates and Time 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!