How to assign different values to different variables at once using deal() function?

조회 수: 22 (최근 30일)
I had some values which are in a single vector named "param". Let us consider it has "n" elements. I want to assign this "n" values to "n" different variables. I'm using deal() function to do this, but I'm not getting the results as I expected.
[a1,a2,a3,..........., an] = deal(param)
I want values to be assigned in this way
a1 = param(1); a2 = param(2) .... , an = param(n)
can someone help me in this regard?
param = [1 2 3 4 5];
[a1,a2,a3,a4,a5] = deal(param)
a1 = 1×5
1 2 3 4 5
a2 = 1×5
1 2 3 4 5
a3 = 1×5
1 2 3 4 5
a4 = 1×5
1 2 3 4 5
a5 = 1×5
1 2 3 4 5
  댓글 수: 3
Dyuman Joshi
Dyuman Joshi 2023년 6월 28일
Any particular reason why you want to do this assignment?
Steven Lord
Steven Lord 2023년 6월 28일
Can you dynamically create variables with numbered names like x1, x2, x3, etc.? Yes.
Should you do this? The general consensus is no. That Answers post explains why this is generally discouraged and offers several alternative approaches.
If the vector you were trying to assign to those variables had 1000, 10000, or more elements do you really want 1000, 10000, or more individual variables in the workspace? Probably not. Instead of assigning to and using (for example) a523 why not just use param(523)?

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

채택된 답변

Jacob Mathew
Jacob Mathew 2023년 6월 28일
Hi Jagadeesh,
The deal function is used to distribute a single input into multiple outputs or multiple inputs into multiple outputs where the number of input and outputs are equal. However the documentation does recommend to use other approaches when possible.
With respect to your query, it is natively not possible to distribute the param variable as you intended. To achieve your desired behaviour, we have to manually convert the param array into a cell array:
param = [1 2 3 4 5];
cellParam = num2cell(param);
[a1,a2,a3,a4,a5] = deal(cellParam{:});
a1
a1 = 1
a2
a2 = 2
a3
a3 = 3
a4
a4 = 4
a5
a5 = 5

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by