Using assignin or evalin command to populate Structure Elements with Numeric Data.

조회 수: 5 (최근 30일)
Hello,
I am getting an error while executing the below command:
assignin('base', 'A.B', 1)|
Error:
??? Error using ==> assignin
Invalid variable name "A.B" in ASSIGNIN.
As a work around i tried to use:
assignin('base', 'temp', 1);
evalin('base','A.B = temp');
evalin('base','clear temp');
The above work around was proposed in one of the previous threads:
The problem I have is that, my Structure elements are read from a Cell Array inside a for loop.
Lets say C = {'A.B', 'A1.B1'}
So how do I pass 'C' as a parameter to the below line:
evalin('base','C = temp')
Expected output: A.B = 1, A1.B1 = 1 (In Base Workspace)
I also tried to use setfield command, but could not succeed.
Thanks, Shyama

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2015년 6월 24일
편집: Azzi Abdelmalek 2015년 6월 24일
For your problem you can use
C = {'A.B', 'A1.B1'}
assignin('base', 'temp', 1);
cellfun(@(x) evalin('base',[x '=temp']),C)

추가 답변 (1개)

Matt J
Matt J 2015년 6월 24일
Not sure why you're not just using setfield(), but another option is
evalin('base','A.B=1');
or
evalin('base',['A.B=' num2str(1)]);
  댓글 수: 1
Shyama Prasad Mishra
Shyama Prasad Mishra 2015년 6월 25일
편집: Shyama Prasad Mishra 2015년 6월 25일
Hi Matt,
I am not using set field because A.B can be any string.
I tried evalin('caller',['setfield(A,''B'',10)']), which works.
How ever when I try to pass the structure name as a string, it does not work.
For Example: C = 'A'; evalin('base',['setfield(C,''B'',10)']) gives an output C.B = 10.
Where as I want the output to be A.B = 10
Am I using Setfield wrongly?

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

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by