I want to assign multiple arrays of data simultaneously to different variable

조회 수: 11 (최근 30일)
I want to assign multiple arrays of data simultaneously to different variable, but I think my syntax is wrong, Can anybody help me out here? A simple version of the code is gioven below.
D=[1 2 3 4 5 6 7 8 9 10];
[p q r]= [D(1:2) D(2:5) D(6:10)]
  댓글 수: 2
Stephen23
Stephen23 2022년 6월 2일
편집: Stephen23 2022년 6월 2일
"I want to assign multiple arrays of data simultaneously to different variable, but I think my syntax is wrong"
It looks as if you are trying to write Python code. If you want to understand what your MATLAB code is actually doing:
  • On the RHS square brackets are a concatenation operator (not a "list" operator, which MATLAB does not have). So your RHS concatenates some arrays together into one array, and is equivalent to this: D([1:2,2:10])
  • On the LHS square brackets are used to capture multiple function outputs. However array concatenation only returns one output, so the code you show will not work: one output cannot be directly assigned to three outputs.
Square brackets are used a lot in MATLAB, you need to understand what they mean and how to use them:
TM Abir Ahsan
TM Abir Ahsan 2022년 6월 2일
@Stephen23 Yes, I understand your point. I think if these were single variables instead of array then my RHS inputs would have been assigned to the individual variables concatanated on the LHS. I was just curious as of why MATLAB could not do the same for arrays instead of single values on the RHS. The deal function is doing exactly what I was looking for here. Thanks for your comment :)

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

채택된 답변

Voss
Voss 2022년 6월 2일
편집: Voss 2022년 6월 2일
D = [1 2 3 4 5 6 7 8 9 10];
[p q r] = deal(D(1:2), D(2:5), D(6:10))
p = 1×2
1 2
q = 1×4
2 3 4 5
r = 1×5
6 7 8 9 10
  댓글 수: 1
TM Abir Ahsan
TM Abir Ahsan 2022년 6월 2일
Amazing! Thanks @Voss, I had no idea about the deal func. Thanks a bunch. This reduced a lot of line of my codes.

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

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by