Data Output as matrix using For Loop
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Yashvardhan Bhati
am 22 Feb. 2022
Kommentiert: Yashvardhan Bhati
am 22 Feb. 2022
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 Kommentare
Akzeptierte Antwort
Arif Hoq
am 22 Feb. 2022
Bearbeitet: Arif Hoq
am 22 Feb. 2022
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 Kommentare
Arif Hoq
am 22 Feb. 2022
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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!