Data Output as matrix using For Loop
조회 수: 2 (최근 30일)
이전 댓글 표시
I have been reading data from matrix Pbc1(30001*3). Now what i want is Sum of all the number present in column 2 within a range of 100 and store them as new matrix. As in, i want to get sum of number from 1-100 present in column 2 and then 101-201 and so on and then store then in new matrix T(300*1).
for n=1:300
s=sum (Pbc1{1+(n-1)*100:n*100,2});
end
but Problem i am facing is s which is output is final sum value i.e sum of number in column 2 of rows 29900-30000 instead of showing all the values. So is it possible to get desired out like below
1 20
2 25
3 60
4 32
and so on.
Other method which i tried was
for n=1:30001:100
s=sum (Pbc1{n:n+100,2});
end
both of them resulted in same answer.
I have attached text file of data.
댓글 수: 0
채택된 답변
Arif Hoq
2022년 2월 22일
편집: Arif Hoq
2022년 2월 22일
You don't need a loop for this. use reshape function
% export data from text file
A=readtable('Pbc1.txt','ReadVariableNames',true);
% this function convert a table format to matrix form.I prefer matrix format instead of table
AA=table2array(A);
% as you will work with second column,so i exported 2nd column only
secondcol=AA(:,2);
% to format in reshape function in next line, i deleted the 1st element
secondcol(1)=[];
% reshape function reshapes a matrix into your expected row and column.
% here 100 rows. [] means matlab will automatically returns the column
% after taking 100 rows.
mat=reshape(secondcol,100,[]);
output=sum(mat)'; % just sum the matrix
댓글 수: 3
Arif Hoq
2022년 2월 22일
My Pleasure.
I have edited some comments in my previous answer. please have a look. for further info type in the command window
doc readtable
doc table2array
doc reshape
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!