How can I get the sum of rows and columns of a table and add them to the table?

13 Ansichten (letzte 30 Tage)
I want to get the totals of each row and column from a table with values inserted by a user
This is my script so far:
row = input('Enter number of rows: ');
col = input('Enter number of columns: ');
for i = 1:row
for j = 1:col
str = ['Enter element in row ' num2str(i) ', col ' num2str(j) ': '];
A(i,j) = input(str);
end
end
A;
See the images for how I want it to look compared to how it looks now

Akzeptierte Antwort

KL
KL am 7 Nov. 2017
Bearbeitet: KL am 7 Nov. 2017
After you get the row and col values from the user, pre-allocate it by,
A = zeros(row+1,col+1);
I say "+1" because that'S where I want to store the sum. Now get the values from user as in the for loop, then to caluclate sum of all rows,
A(end,1:col) = sum(A(1:row,1:col),1); %last element will be 0
to sum all columns
A(1:row,end) = sum(A(1:row,1:col),2); %again, last element will be 0
final result will be like, (for a 3x3 input)
0.8673 0.8289 0.2804 1.9766
0.7212 0.7730 0.7949 2.2891
0.1438 0.3716 0.2151 0.7304
1.7322 1.9735 1.2904 0
  5 Kommentare
Image Analyst
Image Analyst am 8 Nov. 2017
That code still doesn't produce a uitable with any red and black borders, like you wanted and showed in the image you posted.
KL
KL am 8 Nov. 2017
Bearbeitet: KL am 8 Nov. 2017
@Stavro1095: Yes, that's true. This simply creates a matrix in the workspace. If you want to store this matrix in an excel file with custom formatting, you'd have to use ActiveX like IA has suggested.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Image Analyst
Image Analyst am 7 Nov. 2017
Not sure you can do that in MATLAB unless you try some undocumented calls to java. See http://undocumentedmatlab.com/
If you want to make it look like that in an Excel workbook, you can use ActiveX (Windows only) to have MATLAB tell Excel to format the cell shading and borders in any style you want. A generic ActiveX demo is attached.

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by