Question about the syntax of a MATLIB code line creating one array from another
이전 댓글 표시
Hello,
I am working on a MATLAB script that I inherited from a previous programmer and am trying to decipher the syntax of one line. This one line initializes an array called 'x' from another array called 'x0'. There is also a third array called 'indices' that contains the indices of "valid" values of x0. What "valid" means doesn't matter, but let's say for the sake of argument that x0 is a 1x15 array of doubles, and 'indices' is a 1x4 integer array with the values [2 4 7 9]. That's the background.
The assignment statement I have a question about is this, which I'll call Statement #1:
x = [x0(1); x0(indices); x0(end)];
I think the purpose of the above statement is to initialize 'x' to something like this:
x = [x0(1) x0(2) x0(4) x0(7) x0(9) x0(15)];
My question is about the syntax of Statement #1. With the semicolons on its right side, it seems like 'x' would become a 2-dimensional array, and, as I said above, I think the intent was for 'x' to become 1-dimensional array with numel(indices)+2 elements. I think the syntax of Statement #1 should therefore replace the semicolons with commas to give the desired result. Am I right?
댓글 수: 1
As you described it the code would throw an error:
x0 = 1:15; % 1x15
indices = [2,4,7,9]; % 1x4
[x0(1);x0(indices);x0(end)]
"I think the syntax of Statement #1 should therefore replace the semicolons with commas to give the desired result."
Most likely the answer to your question is answered in the following code: what orientation does the rest of the code require?
채택된 답변
추가 답변 (1개)
To answer this, you have to know that the result of indexing a column vector with a single vector is a column vector, and the result of indexing a row vector with a single vector is a row vector:
A = [1 2 3]
A(2:3)
A((2:3)')
B = [1; 2; 3]
B(2:3)
B((2:3)')
So the shape of the indexing vector does not matter in this context.
The behaviour is different when it is a 2D array being indexed:
C = [1 2 3; 4 5 6]
C(2:3)
C((2:3)')
In this 2D case, the shape of the indexing vector does matter.
댓글 수: 1
dpb
2024년 10월 31일
That points out the thing I asked @Michael McCully about, @Walter Roberson of whether he's missing seeing a transpose operation somewhere such that his description of x0 as a row vector is incorrect in his actual code and that having only his description of the code isn't the same as having the code itself.
카테고리
도움말 센터 및 File Exchange에서 Communications Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!