フィルターのクリア

problem with eval notation

1 回表示 (過去 30 日間)
Tor Fredrik Hove
Tor Fredrik Hove 2011 年 10 月 26 日
I have a question about eval in this script
function sort=sortstructure(strucvector, field)
if isfield(strucvector,field)
for i=1:length(strucvector)-1
low=i
for j=i+1:length(strucvector)
if eval(['strucvector(' num2str(j) ' ). ' field])<...
eval(['strucvector(' num2str(low) ' ). ' field])
low=j
end
end
temp=strucvector(i)
strucvector(i)=strucvector(low)
strucvector(low)=temp
end
else disp('wrong field')
end
sort=strucvector
Why cab't I write the part with eval like this:
if eval(['strucvector(num2str(j)).''field'])<...
eval(['strucvector(num2str(low)).''field'])
I know eval is often considered unhandy but it is part of curriculum
  1 件のコメント
Daniel Shub
Daniel Shub 2011 年 10 月 26 日
The eval is only there because the curriculum is dated to before MATLAB handled dynamic field names.

サインインしてコメントする。

採用された回答

Sean de Wolski
Sean de Wolski 2011 年 10 月 26 日
I don't see any reason for eval above. If you get rid of it, it should still run. If you're required by law of the professor to use it, have it do something useless and not dangerous at the end.
E.g.
%the rest of the code
eval('disp(''we did it!'')')
  3 件のコメント
Daniel Shub
Daniel Shub 2011 年 10 月 26 日
I believe in MATALB x.y, where x is smaller than I care to go back to figure out its actual value, the eval was required.
Daniel Shub
Daniel Shub 2011 年 10 月 26 日
@Tor, it is not really working when you remove the eval. You are in fact doing a comparison of two strings. It gives you an error (I am guessing something about matrix dimensions), when you delete a space from the j side and not a space in the low side.

サインインしてコメントする。

その他の回答 (2 件)

Daniel Shub
Daniel Shub 2011 年 10 月 26 日
You cannot do
eval(['strucvector(num2str(j)).''field'])
because
['strucvector(num2str(j)).''field']
expands to a string of strucvector(num2str(j)).'field (notice the odd '). EVen if you eliminate the odd ', you won't get the correct answer.
strucvector(num2str(j)).field
will essentially do
strucvector(double(num2str(j))).field
which is not:
strucvector(j).xxx
where xxx is whatever string is contained in field.
That is why you cannot do what you want and the original version works.
Current versions of MATLAB all for
strucvector(j).(field)

Wayne King
Wayne King 2011 年 10 月 26 日
Hi Tor, Not sure why you want to use eval() here, but:
test = struct('data',randn(10,1));
for nn = 1:9
if (eval('test.data(nn) < test.data(nn+1)'))
disp('hi'); end
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by