The lines inside my while-loop are never executed

function lagre(filename)
res = 1;
fid = fopen(filename,'w');
while (res ~= [])
res = input('Type in text that you want to save, and press Enter. Leave a blank space and press Enter to quit.');
fprintf(fid, '%s \n', res);
end
fclose(fid);
end
The lines inside this while-loop are never executed, and I don't understand why. 1 is certainly unequal to nothing, right?

回答 (1 件)

dpb
dpb 2014 年 12 月 2 日

0 投票

...1 is certainly unequal to nothing, right?
Yabbut... :)
The ~= comparison fails because the two results are incompatible in type/class.
Use
while ~isempty(res)
instead.

1 件のコメント

Guillaume
Guillaume 2014 年 12 月 2 日
To add to that, matlab has many different ways to arrive at the empty set, none of which it considers equal with isequal. With == you have the additional problem that these empty have different sizes (sic!)
a = 1;
a(1) = []; % a is now empty
isequal(a, []) %return false!
isequal(a, double.empty(0,1)) %return false!
a == [] %error dimension not equal
Always use isempty to test for emptiness.

この質問は閉じられています。

タグ

質問済み:

2014 年 12 月 2 日

閉鎖済み:

2021 年 8 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by