How do i add all the values which i get using eval function?

조회 수: 3 (최근 30일)
DIJESH
DIJESH 2014년 5월 27일
댓글: DIJESH 2014년 5월 27일
prompt = {'Enter the forces(kN): '};
title = 'Environmental forces';
answer = inputdlg(prompt,title);
f = str2num(answer{:});
for ii=1:numel(f)
eval(sprintf('f%d = %f\n',ii,f(ii)))
end
prompt1 = {'Enter the respective angles: '};
title1 = 'Angle w.r.t x-axis';
answer1 = inputdlg(prompt1, title1);
a = str2num(answer1{:});
for jj=1:numel(a)
eval(sprintf('a%d = %f\n',jj,a(jj)))
end
for jj=1:numel(a)
string='f(jj)*cos(jj)';
eval(string)
end
in this code i am getting several values for string. I have to add all those values. can anyone help?

채택된 답변

Jos (10584)
Jos (10584) 2014년 5월 27일
Avoid EVAL !!!
You do not want to store a series of related values in separate variables f1 = .. f2 = .. but rather in a single variable with multiple elements f(1) = .. f(2) = ..
Your codes is almost there. Just remove the evals ...
prompt = {'Enter the forces(kN): '};
title = 'Environmental forces';
answer = inputdlg(prompt,title);
f = str2num(answer{:});
prompt1 = {'Enter the respective angles: '};
title1 = 'Angle w.r.t x-axis';
answer1 = inputdlg(prompt1, title1);
a = str2num(answer1{:});
if numel(f) ~= numel(a)
error('The vectors should have the same number of elements') ;
else
sum=0 ;
for jj=1:numel(a)
sum = sum + f(jj)*cos(a(jj)) ;
end
% or use the power of matlab:
% sum = sum(f.*cos(a))
end
Lesson to be learned: avoid eval!

추가 답변 (1개)

rifat
rifat 2014년 5월 27일
prompt = {'Enter the forces(kN): '};
title = 'Environmental forces';
answer = inputdlg(prompt,title);
f = str2num(answer{:});
for ii=1:numel(f)
eval(sprintf('f%d = %f\n',ii,f(ii)))
end
prompt1 = {'Enter the respective angles: '};
title1 = 'Angle w.r.t x-axis';
answer1 = inputdlg(prompt1, title1);
a = str2num(answer1{:});
for jj=1:numel(a)
eval(sprintf('a%d = %f\n',jj,a(jj)))
end
sum=0;
for jj=1:numel(a)
string='f(jj)*cos(jj)';
sum=sum+eval(string);
end

카테고리

Help CenterFile Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by