Summing elements of a vector without a for loop
    조회 수: 5 (최근 30일)
  
       이전 댓글 표시
    
Given a vector/array v  of length  ,  I would like to create a new vector of length M where the 1st component is the sum of the 1st 5 elements of v, the 2nd element is the sum of the next 5 elements of v,... and so on until we get to the last element which is the sum of the last 5 elements of v.
,  I would like to create a new vector of length M where the 1st component is the sum of the 1st 5 elements of v, the 2nd element is the sum of the next 5 elements of v,... and so on until we get to the last element which is the sum of the last 5 elements of v. 
 ,  I would like to create a new vector of length M where the 1st component is the sum of the 1st 5 elements of v, the 2nd element is the sum of the next 5 elements of v,... and so on until we get to the last element which is the sum of the last 5 elements of v.
,  I would like to create a new vector of length M where the 1st component is the sum of the 1st 5 elements of v, the 2nd element is the sum of the next 5 elements of v,... and so on until we get to the last element which is the sum of the last 5 elements of v. Is there a quick way to do this without using a for loop? 
댓글 수: 0
채택된 답변
  Yongjian Feng
    
 2021년 10월 29일
        
      편집: Yongjian Feng
    
 2021년 11월 2일
  
      How about this:
M=3; % you know your M
v = ones(1, M^2); % your v vector
vReshaped = reshape(v, M, M)'; % Note need this.
result = sum(vReshaped, 2)';
댓글 수: 3
  Stephen23
      
      
 2021년 11월 2일
				n = 3;
v = 1:9; % square brackets are not required
r = sum(reshape(v,n,n),1) % transpose is not required
추가 답변 (1개)
참고 항목
카테고리
				Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



