Hi!
I have a problem with cell contents...
I have 2 cells
C1={'abc','def','ghi'}
C2={'1','2','3'}
I want to create a variable from the content of C1 with the value of C2.
abc=1
def=2
ghi=3
Those variables should be created automatically within a loop, because the original cells are bigger than 3 values.
I hope someone can help me with that problem. Thank you very much!

답변 (1개)

Stephen23
Stephen23 2021년 3월 29일

0 개 추천

Simpler and much more efficient than what you are attempting is to use a basic structure:
C1 = {'abc','def','ghi'};
C2 = {'1','2','3'};
S = cell2struct(num2cell(str2double(C2)),C1,2);
S.abc
ans = 1
S.ghi
ans = 3

댓글 수: 4

Christian Gapick
Christian Gapick 2021년 3월 29일
Those cell arrays were only examples.
The original cells are more complex and there is no need for putting them in a struct for my intentions.
I think I found a solution with your comment and the function "eval".
Thank you very much !
Rik
Rik 2021년 3월 29일
Then you didn't understand the link well enough. You should not use eval. That will harm you in the long run. It is easy to learn bad coding behaviour, it is hard to un-learn them.
Christian Gapick
Christian Gapick 2021년 3월 29일
Oh.. now I read a lot of "evil EVAL" comments. Unfortunately I didn't find a proper way to transmit the variables to the workspace without using eval.
Para_p is my cell array with all variable names I need and Para_p_value contains the values for those variables.
for m=1:length(Para_p)
eval([Para_p{m},'=[',num2str(Para_p_value{m}),']',]);
end
This returns all variables connected to their values and transmit them to the workspace.
And unfortunately all variables need to be defined individual, because the software needs them like this. So I can't put them in a struct.
Is there any possibility to avoid eval in this case ?
Rik
Rik 2021년 3월 29일
The flaw is with the software that requires this. What is this strange software that needs variables to have a specific name? Why isn't that a function (which wouldn't care about the variable name in the caller)?
The code you show is one of two way I know. The other way would be to store to a struct, saving that to a mat file with the '-struct' flag and loading without an output to poof the variables into existence. You should use neither.
The solution is to change that script you're calling to a function. If you make a brigde out of spaghetti, the solution is not to use water-repelling glue, the solution is to switch to steel.

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

카테고리

도움말 센터File Exchange에서 Function Creation에 대해 자세히 알아보기

질문:

2021년 3월 29일

댓글:

Rik
2021년 3월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by