Initializing 1/2 of a row with one value and the other half with another

15 次查看(过去 30 天)
I don't understand why the following works. It initializes row 1 of the array c with values of 1 in roughly the first half of the columns and then places a zero in the exact middle column (half way) while also placing zeros in the right half of the columns. So, if the number of columns is 11, columns 1 through 5 are initialized with 1 and columns 6 through 11 with zero.
1) c(1,:)=[ones(1,(N-1)/2),zeros(1,(N+1)/2)]
I would have thought that the way to do this is to specify the zeros from columns (N+1)/2 to N. More like:
2) c(1,:)=[ones(1,(N-1)/2),zeros((N+1)/2,N)]
So if N = 11, the script, 2) would result in:
c(1,:)=[ones(1,(10)/2),zeros((11+1)/2,11)] or c(1,:)=[ones(1,5),zeros(6,11)]
So, Matlab just knows that in 1) above to continue counting from the column where it stopped putting ones to start putting in values of zeros for the remaining columns. So, rather than an absolute reference like I've shown in 2), it uses a relative reference to decide which columns to initialize?

采纳的回答

David Hill
David Hill 2021-6-8
You are concatenating two arrays. Look at the ones() and zeros() functions.
a=ones(1,5);
b=zeros(1,6);
c=[a,b];
  2 个评论
Robert Demyanovich
编辑:Robert Demyanovich 2021-6-8
I forgot to mention that prior to the script I posted above, there is the following statement:
c=zeros(M,N)
where M is the number of rows and N is the number of columns as before.
So the entire array is first initialized with zeros.
c=[a,b] concatenates arrays a and b. But because of the statement c=zeros(M,N), how can concatenation occur within an already defined array that is already the size of the final concatenation (with respect to the number of columns)??
So does this mean that if c doesn't exist, the following creates a new array
c=[a,b]
but if c does already exist, then only the values of a and b are concatenated within the existing array, c. I would appreciate it if someone could confirm this for me.
David Hill
David Hill 2021-6-8
编辑:David Hill 2021-6-8
because you are specifing:
c(1,:)=[a,b];%you are only doing it to the first row of c
% you could also do it the the 5th row
c(5,:)=[a,b];
%or you could do it to all odd rows of c
c(1:2:end,:)=[a,b];

请先登录,再进行评论。

更多回答(1 个)

Fangjun Jiang
Fangjun Jiang 2021-6-8
编辑:Fangjun Jiang 2021-6-8
You mis-understood it. The code involves built-in functions ones() and zeros(). The input arguments are size of the matrix, not the index of elements in a matrix.
The "[ ]" operator combines the two matrix (or vectors, five ones and six zeros) together.
Or you could do this
N=11
c(1,1:(N-1)/2)=1
c(1,(N+1)/2:N)=0

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by