sábado, 11 de enero de 2014

[Ejercicio resuelto Java] Sumar dos matrices de orden nxn – Platform – Teleconferencias – Register


Hace poco coloque una entrada sobre comoSumar dos matrices de orden 2x2 en java. Pero que sucedería si nuestras matrices no son tan simples y éstas son de otro orden, quizás de 3x3, 4x4, 5x4, 4x2... entre otras posibilidades.

A continuación les muestro como podemos sumar matrices de orden nxn usando java.


nxn.java
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.util.Scanner;

public class nxn {
private Scanner tec;
private int[][] matrizA;
private int[][] matrizB;
private int[][] matrizC;
private int filas, columnas;


public void CargarElementos(){
tec = new Scanner(System.in);
System.out.println("Ingrese la cantidad de filas de las matrices");
filas = tec.nextInt();
System.out.println("Ingrese la cantidad de columnas de las matrices");
columnas = tec.nextInt();
matrizA = new int[filas][columnas];
matrizB = new int[filas][columnas];
System.out.println("Ingrese los elementos de la matriz A: \n");
for(int i=0; i filas; i++){
int f=i+1;
for(int j=0; j columnas; j++){
int c = j+1;
System.out.println("Ingrese el elemento a"+f+c + " de la matriz");
matrizA[i][j] = tec.nextInt();
}
}

System.out.println("\nIngrese los elementos de la matriz B: \n");
for(int i=0; i filas; i++){
int f=i+1;
for(int j=0; j columnas; j++){
int c = j+1;
System.out.println("Ingrese el elemento b"+f+c + " de la matriz");
matrizB[i][j] = tec.nextInt();
}
}
}

public void Suma(){
matrizC = new int[filas][columnas];
for(int i=0; i filas; i++){
for(int j=0; j columnas; j++){
matrizC[i][j] = matrizA[i][j] + matrizB[i][j];
}
}
}

public void Imprimir(){
//Matriz C:
System.out.println("La Suma de ambas matrices es:");
for(int i = 0; i filas; i++){
System.out.println("");
for(int j=0; j columnas; j++){
System.out.print(matrizC[i][j] + " ");
}
}
//-----------------------------------------------------------------
System.out.println("\n Elementos de la matriz C: \n");
for(int i=0; i filas; i++){
int f=i+1;
for(int j=0; j columnas; j++){
int c = j+1;
System.out.println("Elemento c"+ f + c + ": " + matrizC[i][j]);
}
}
}

public static void main(String[] ar){
nxn n = new nxn();
n.CargarElementos();
n.Suma();
n.Imprimir();
}
}

Inicialmente leemos mediante el teclado la cantidad de filas y columnas de nuestras matrices.La teoría de matrices nos dice que para sumar dos matrices éstas deben ser del mismo orden, por ello no leemos el orden de las matrices por separado, sino que leemos una sola vez para ambas matrices.

Necesitaremosdos ciclos for, uno que se repetirá tantas veces como filas posean las matrices, es decir, representa la cantidad de filas de las matrices. El otro ciclo for debe ir dentro del anterior, éste se repetirá tantas veces como columnas posean las matrices.Sí lo vemos, ésto nos da la posibilidad de ir asignando valores a los componentes de la matriz uno por uno. a11, a12, 13, a1n... a21, a22, a23, a2n... ann...

Las lineas int f = i+1 y int c = j+1 nos ayudan a dar un mensaje al usuario refiriéndonos a los componentes de las matrices de una manera matemática,hay que recordar que en java el primer elemento en una matriz es el a00, pero en matemáticas (álgebra lineal) el primer elemento es a11. Por lo tanto, si aij = a00 entonces, como f=i+1 y c=j+1 ; afc = a11.

Tanto para leer, sumar e imprimir los elementos de las matrices usaremos los dos ciclos for, es decir, trabajaremos análogamente para realizar dichas tareas.

Además, para sumar ambas matrices lo que haremos será tener una nueva matriz la que llamaremos matrizc[i][j] en la cual almacenaremos los componentes de las matrices A y B sumados.

Nota: Si desean saber un poco mas sobre matrices en java pueden observar la siguiente entrada:

Finalmente la salida sería la siguiente:



what is structured settlement Insurance Companies Php programmers Criminal lawyer WordPress themes for designers Online casino Casino maritime lawyer houston New social media platforms ONLINECLASSES refinance with bad credit ASBESTOS LAWYERS chicago hair laser removal small business administration sba firm law mesothelioma Online Christmas cards Mobile casino peritoneal mesothelioma Online colledges broward county dui lawyer PSYCHIC FOR FREE domains yahoo donate your car for kids Social media platforms boca raton personal injury attorney DONATING USED CARS TO CHARITY home phone internet bundle Computer science classes online Donate a Car in Maryland mesothelioma suit Annuity Settlements baltimore mesothelioma attorneys PhD in counseling education Casino reviews Motor Insurance Quotes Nunavut Culture mesothelioma lawyer texas CRIMINAL DEFENSE ATTORNEYS FLORIDA DONATING A CAR IN MARYLAND Php programmers for hire Donate Car to Charity California cheap auto insurance in va Auto Mobile Shipping Quote Adobe illustrator classes Best Criminal Lawyers in Arizona Make money online Australia mesotheliama Best social media platforms Custom Christmas cards Service business software Hire php developer cell cycle regulation ppt workplace accident attorney holland michigan college car insurance in south dakota DONATE CAR FOR TAX CREDIT Asbestos Lawyers CAR DONATE Live casino Hire php developers DONATE CARS IN MA Online Classes DUI lawyer Hire php programmers mesothelioma settlements Dwi lawyer Better Conference Calls caraccidentlawyer Injury Lawyers accident attorney san bernardino Criminal lawyer Miami Royalty Free Images Stock Automobile Accident Attorney Met auto Criminal defense lawyer california mesothelioma attorney Best social media platforms for business Bankruptcy lawyer fast cash for house mesothelioma lawyers san diego verizon sip phd in counseling education Social media platforms for business mesothelioma settlements amounts PHD IN COUNSELING EDUCATION colorado auto accident attorney AUTOMOBILE ACCIDENT ATTORNEY Holland Michigan College ashely madis att call conference car insurance companies Seo companies Better conferencing calls Social media strategies Donate Cars Illinois Mesothelioma Law Firm asterisk call center software Business finance group Psd to html Best Seo company auto insurance cost by state Psychic for Free Hard drive data recovery services structured settlements annuities how to donate a car in california Seo services DONATE YOUR CAR FOR MONEY Proud Italian cook World trade center footage Social media tools Custom WordPress theme designer Cheap car insurance for ladies Social media examiner Donate Cars in MA auto accident attorney Torrance personal injury solicitor cash out structured settlement miami personal injury attorney Psychic for free Online Colleges mesothelioma attorney CAR INSURANCE QUOTES UTAH WordPress theme designers ROYALTY FREE IMAGES STOCK Business management software Tech school Seo company Car Insurance Quotes Utah Html email Donate car for tax credit World Trade Center Footage PHD on Counseling Education Photo Christmas cards WordPress hosting Psd to WordPress Home Phone Internet Bundle Best criminal lawyer in Arizona Donating a car in Maryland california motorcycle accident lawyer Social media management Dallas mesothelioma attorneys anti spam appliance new mexico mesothelioma lawyer Car Insurance Quotes Colorado Email bulk service Auto Accident Attorney Virtual Data Rooms car donate structured settlement brokers Mortgage adviser Christmas cards AUTO ACCIDENT ATTORNEY federal criminal defense attorney DONATE A CAR IN MARYLAND Royalty free images stock Italian cooking school CAR INSURANCE QUOTES PA MORTGAGE ADVISER Dedicated Hosting Dedicated Server Hosting webex costs tucson car accident attorney FORENSICS ONLINE COURSE LOW CREDIT LINE CREDIT CARDS Learning adobe illustrator Donating a Car in Maryland HOLLAND MICHIGAN COLLEGE Social media campaigns donate old cars to charity car insurance quotes BETTER CONFERENCING CALLS paperport promotional code MASSAGE SCHOOL DALLAS TEXAS register free domains Donate Car for Tax Credit Donate Your Car Sacramento How to Donate A Car in California Met Auto Sell Annuity Payment Donate Your Car for Kids supportpeachtreecom florida car insurance company CHEAP DOMAIN REGISTRATION HOSTING Cheap Car Insurance in Virginia city college in miami Structures Annuity Settlement mesothelioma lawyer houston mesothelioma law firm Business Voip Solutions virtual data rooms Dayton Freight Lines Hard drive Data Recovery Services Dallas Mesothelioma Attorneys criminal defense attorneys florida structured settlement annuity companies mesothelioma attorneys sell my structured settlement Motor Replacements Webex Costs Cheap Domain Registration Hosting annuity payment Donate Old Cars to Charity Criminal Defense Attorneys Florida mesothelioma attorney illinois car accident lawyers la personal injury lawyer primary pulmonary hypertension Life Insurance Co Lincoln SELL ANNUITY PAYMENT HARDDRIVE DATA RECOVERY SERVICES Online Motor Insurance Quotes Email Bulk Service mesotheolima Paperport Promotional Code accident attorneys orange county Massage School Dallas Texas washington mesothelioma attorney Donate your Car for Money Donate your car for money Mortgage Low Credit Line Credit Cards Car Insurance Quotes MN Cheap Auto Insurance in VA Forensics Online Course Donating Used Cars to Charity hair removal washington dc Neuson Car Insurance Quotes PA Car Insurance in South Dakota Online Criminal Justice Degree mesothelioma charities Cheap Car Insurance for Ladies low credit line credit cards Register Free Domains buying an annuity calculator Futuristic Architecture DONATE OLD CARS TO CHARITY hughes net business Mortgage Adviser saskatchewan auto insurance michigan motorcycle accident lawyer Car Donate motor insurance quotes Online College Course business email web hosting structured settlement sell personal injury accident lawyer Car Accident Lawyers Data Recovery Raid DONATE YOUR CAR SACRAMENTO CAR INSURANCE QUOTES COLORADO

No hay comentarios:

Publicar un comentario