필터 지우기
필터 지우기

problem with code

조회 수: 1 (최근 30일)
Tor Fredrik Hove
Tor Fredrik Hove 2011년 10월 22일
I am trying a script that does not work. First I define a structure in matlab:
>> package=struct('item_no',123,'cost',19.99,'price',39.95,'code','g')
package =
item_no: 123
cost: 19.9900
price: 39.9500
code: 'g'
then I have made a script who will try to find out the value of a field in the structure:
inputfield=input('Which field would you like to see: ','s')
if isfield(package, inputfield)
fprintf('The value of the %s field is: %c\n',inputfield,...
eval(['package.'inputfield]))
else
fprintf('Error: %s is not valid field\n', inputfield)
end
but i get error message:
>> structurevalue ??? Error: File: structurevalue.m Line: 6 Column: 22 Unexpected MATLAB expression.

채택된 답변

Mitch Martelli
Mitch Martelli 2011년 10월 22일
the problem is in the eval,try to put a blank after 'package.' :
eval(['package.' inputfield])
  댓글 수: 5
Tor Fredrik Hove
Tor Fredrik Hove 2011년 10월 22일
Hi Image Analyst! I am a bit new with matlab so convenient choices is not my strong side. Eval is also a part of the curriculum so I have to know something about it either way
Jan
Jan 2011년 10월 22일
I do not understand what "is part of the curriculum" means. Using EVAL is a bad programming practize, because it is prone to errors and results in slow code.
"package.(inputfield)" is much safer and faster than "eval(['package.' inputfield])".

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2011년 10월 22일
This is what the line should look like:
fprintf('The value of the %s field is: %c\n',inputfield, package.(inputfield));
Look up "dynamic field names" in the help for more info.
  댓글 수: 1
Jan
Jan 2011년 10월 22일
+1: Best answer. Perhaps ignoring your answers is a running joke. However, I'm missing the punchline.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by