viernes, 26 de junio de 2015

Que son las Matrices en Java (Arreglos Bidimensionales)

En una entrada anterior hablamos sobre los Arreglos unidimensionales, en esta ocasión vamos a continuar con la entrada pero ahora conociendo las Matrices o arreglos bidimensionales!!!!

   
¿Que son?

Este tipo de arreglos son conocidos como matrices y corresponden a una estructura de datos que puede almacenar muchos más datos que los arreglos unidimensionales, pues estos últimos como ya se mencionó se componen de una fila por n columnas, mientras que los bidimensionales se componen de n filas por m columnas.

Como se ve en la imagen, se tiene un arreglo de 3 filas por 4 columnas siendo n=3 y m=4, la lógica de la estructura es muy similar a los arreglos unidimensionales, cada índice inicia en 0 hasta el tamaño-1 por esa razón las posiciones de las filas van de 0 a 2 y el de las columnas de 0 a 3.

Se puede ver que la matriz anterior es como si fueran 3 arreglos de tamaño 4 juntos, pues se puede entender cada fila como uno de ellos, por lo tanto la declaración, construcción e inicialización es muy similar.


Declaración de Matrices.

Las matrices se identifican porque al momento de su creación se utilizan doble corchetes ( [ ] [ ]), al usarlos java automáticamente identifica que se va a trabajar con matrices, ya que representan el tamaño de filas por columnas que puede tener, igual que los arreglos unidimensionales se tienen 2 formas generales para su creación.

              <tipoDato>  identificador[ ] [ ];           Ej:  int matrizDeEnteros[ ] [ ];

O también

              <tipoDato>[ ] [ ]  identificador;         Ej:  int[ ] [ ] matrizDeEnteros;

Donde tipo de dato define el tipo de dato de cada uno de los valores que puede contener la matriz.


Construcción de la Matriz.

Después de haber declarado la matriz se puede construir e inicializar de 2 maneras.

Forma1.
la primera se usa cuando inicialmente no sabemos cuáles son los valores que va a contener la matriz, ya que luego serán ingresados, se crea con la siguiente estructura:
 

Identificador = new <tipoDato> [filas] [columnas];       Ej. matrizDeEnteros = new int[3] [4];

Podemos observar como la matrizDeEnteros declarada previamente, ahora es creada con un tamaño de 3 x 4 (3 filas 4 columnas) creándose un total de posiciones de memoria equivalente a la multiplicación de estos valores, así estas posiciones corresponden a un espacio donde se pueden almacenar 12 datos de tipo int.


Inicialización de la Matriz.

Igual que con los arreglos, se deben tener presente el tamaño asignado para las filas y columnas pues cada posición almacenará un valor del tipo de dato declarado para la matriz, el llenado se realiza de la siguiente manera:

          identificador[fila] [columna]=dato;          

Sabemos que el identificador corresponde al nombre de la matriz, posición a alguna de las casillas y dato el valor a asignar, que debe ser del tipo de dato definido al momento de la creación.


Forma 2.
De la misma manera que la segunda forma de llenado de arreglos, para las matrices se usa cuando sabemos con exactitud cuáles son los valores que va a contener la matriz, aquí el proceso de construcción e inicialización se hace directo y se realiza de la siguiente manera:
 

Identificador = { {valor, valor,valor}, {valor, valor,valor}, {valor, valor,valor} };

Dónde:
Identificador: nombre de la matriz
Llaves externas: representa toda la matriz en general
Llaves internas: representan cada una de las filas que puede contener la matriz
Valores: representan los valores de cada columna en la fila respectiva

Como vemos en la estructura, se está creando una matriz de 3x3, pues hay 9 valores repartidos en 3 grupos correspondientes a las filas los cuales se muestran encerrados en las llaves internas.


Como se puede observar no fue necesario indicar cuál es el tamaño de la matriz, ya que java identifica el tamaño gracias a las posiciones y cantidad de valores separados por coma. 

Acceso a los datos de una matriz.

Para acceder a la información almacenada dentro de una matriz se debe tener presente el nombre de la matriz, tamaño y el tipo de datos que contiene.

Por ejemplo, si queremos almacenar un dato de una variable, la forma de acceder es por medio de los  índices de fila y columna que corresponde a la posición del valor a obtener:

             variable = Identificador[fila] [columna];


donde la variable corresponde a una variable del tipo de dato que se quiere almacenar, el identificador corresponde al nombre de la matriz y la posición a alguno de los valores entre 0 y tamaño-1 (tanto para fila como para la columna)

Tomando el ejemplo de la matriz anterior, queremos obtener el valor en la posición (2,3) de la matriz (ver imagen anterior).

Entonces:

           int dato= matrizDeEnteros [2] [3];

Por lo tanto dato, almacenará el valor 16.


Ejemplo Forma 1.
 
Ejemplo Forma 2.

 Ahora miremos el siguiente ejemplo donde se creará la misma matriz anterior pero usando la segunda forma trabajada.




Llenado y consulta de datos del arreglo por medio de ciclos.

Cuando se desea llenar un arreglo de muchas posiciones, los ciclos juegan un papel muy importante ya que nos permitirán hacer este proceso más dinámico, pues podemos recorrer cada posición usando la variable de incremento, tanto para asignar como para obtener.


Teniendo en cuenta que siempre cuando asignamos o consultamos datos del arreglo, debemos indicar cuál es la posición o índice que vamos a usar, la posición podemos trabajarla como una variable que toma  cada uno de los valores posibles que a  tomar.

Ej: arreglo[posición]=valor  //asignación valor en el arreglo
      Variable=  arreglo[posición] //asignación valor del arreglo en la variable.




El ejemplo anterior realiza un proceso similar al llenado y búsqueda de un arreglo, esta vez note que se utilizan 2 ciclos anidados tanto para el llenado como la consulta de los datos.

El primer ciclo for lo que hace es recorrer cada una de las filas, caso contrario el segundo recorre las columnas, de este modo se puede usar el proceso matriz[i][j] para ir almacenando los datos en cada posición dado el vector (i,j) que representa (filas,columnas).


Te comparto este video adicional donde complementas lo visto en esta entrada...

 


También te podría Interesar.


¿Hay algo que quieras anexar o comentar sobre esta entrada?  no dudes en hacerlo.....y si te gustó...... te invito a compartir
 y Suscribirte ingresando al botón "Participar en este sitio" para darte cuenta de mas entradas como esta ;)

97 comentarios:

  1. Disculpen! en el caso que tenga que hacer la multiplicación de dos matrices? :/ he intentado, pero no puedo. De antemano, agradezco su ayuda!!

    ResponderEliminar
    Respuestas
    1. Great Article android based projects

      Java Training in Chennai Project Center in Chennai Java Training in Chennai projects for cse The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai

      Eliminar
  2. QUE TAL

    ME GUSTO LA PAGINA EXCELENTE EXPLICACION.

    SALUDOS

    LORDESTRUCTION

    ResponderEliminar
  3. Hola, excelente tu blog y tus videos de youtube, sería posible que explicaras como
    recorrer matrices en diferentes formas, por ejemplo en diagonal, en forma de serpiente, en caracol, etc.

    De antemano gracias por ayudar a los que apenas estamos comenzando a programar.

    Saludos

    ResponderEliminar
  4. una pregunta como se puede hacer busqueda de registros en un arreglo multidimensional de string en java

    ResponderEliminar
  5. Muy buenos dias/tardes lo que corresponda, solo decir que buscando ejercicios basicos llegue a ustedes y encuentro bueno su material, pero queria solo acotar…(y muy en buena y con toooodo el respecto del mundo!!!!) mecanizar a que siempre en un for, en if o similares se debe colocar entre llaves { } A UNA UNICA INSTRUCCION NO ES NADA BUENO para novatos o aprendices. Y aunque paresca despreciable el detalle o que da igual el uso de llaves debe ser para mas de una instruccion sino es redundante y no apunta a crear codigo limpio, claro, en especial para codigos profesionales de miles y miles de lineas. Ademas que exigue, si exigue, mas al compilador. Programo y enseño como docente desde los 90’s y creo que es mejor enseñar bien desde el inicio y con estos detalles que en algunos lugares pasan desapercibidos.

    Atte, prof. RAUL C. S.
    Lic. en Cs de la Computacion, USACH

    ResponderEliminar
  6. perfect explanation about java programming .its very useful.thanks for your valuable information.java training in chennai | java training in velachery

    ResponderEliminar
  7. Thanks for sharing such informative guide on java Code technology. This post gives me detailed information about the program technology.
    {We have Best Online Training Institutes for follows devops Training | devops Online Training Training | Learn devops Online Training | devops Training Institutes}

    ResponderEliminar
  8. perfect explanation about java programming .its very useful.thanks for your valuable information.java training in chennai | java training in velachery

    ResponderEliminar
  9. I simply want to say I’m very new to blogs and actually loved you’re blog site. Almost certainly I’m going to bookmark your blog post . You absolutely come with great well written articles. Thanks a lot for sharing your blog.
    java training in chennai | chennai's no.1 java training in chennai | best java institute in chennai

    ResponderEliminar
  10. Gracias, bien explicado.
    En "Acceso a los datos de una matriz." hay un pequeño error el resultado debería ser "1".

    ResponderEliminar
  11. excelente, gracias
    una pregunta, como puedo recorrer la matriz por filas pero de izquierda a derecha?

    ResponderEliminar
  12. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.

    DevOps Training in Chennai

    ResponderEliminar
  13. Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp great deal more around this condition.


    DevOps Training in Bangalore

    ResponderEliminar
  14. Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp great deal more around this condition.
    datascience training in chennai

    ResponderEliminar
  15. Es buena y clara la explicacion... pero ojo hay un error en Acceso a los datos de una matriz:
    En
    int dato= matrizDeEnteros [2][3];

    Por lo tanto dato, almacenará el valor 16. La respuesta 16 es erroneo la correcta es 13... ya que es el dato de las coordenadas fila Nº2 (se comienza desde 0) y columna Nº 3 (se comienza desde 0)

    ResponderEliminar
  16. Existing without the answers to the difficulties you’ve sorted out through this guide is a critical case, as well as the kind which could have badly affected my entire career if I had not discovered your website.
    Digital Marketing Training in Chennai

    Digital Marketing Training in Bangalore

    digital marketing training in tambaram

    digital marketing training in annanagar

    digital marketing training in marathahalli

    ResponderEliminar

  17. It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Fantastic read.

    Digital Marketing Training in Mumbai

    Six Sigma Training in Dubai

    Six Sigma Abu Dhabi

    ResponderEliminar
  18. Great content thanks for sharing this informative blog which provided me technical information keep posting.
    AWS Training in chennai

    AWS Training in bangalore

    ResponderEliminar
  19. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    Devops Training in Chennai

    Devops Training in Bangalore

    ResponderEliminar
  20. All the points you described so beautiful. Every time i read your i blog and i am so surprised that how you can write so well.
    Blueprism training in tambaram

    Blueprism training in annanagar

    Blueprism training in velachery

    ResponderEliminar
  21. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

    rpa training in Chennai | rpa training in pune

    rpa training in tambaram | rpa training in sholinganallur

    rpa training in Chennai | rpa training in velachery

    rpa online training | rpa training in bangalore

    ResponderEliminar
  22. The site was so nice, I found out about a lot of great things. I like the way you make your blog posts. Keep up the good work and may you gain success in the long run.
    python online training
    python training in chennai

    ResponderEliminar
  23. This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    java training in tambaram | java training in velachery

    java training in omr | oracle training in chennai

    ResponderEliminar
  24. Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
    Good discussion. Thank you.
    Anexas
    Six Sigma Training in Abu Dhabi
    Six Sigma Training in Dammam
    Six Sigma Training in Riyadh

    ResponderEliminar
  25. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    java training in omr | oracle training in chennai

    java training in annanagar | java training in chennai

    ResponderEliminar
  26. Inspiring writings and I greatly admired what you have to say, I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information ..
    Sql&Plsql Training From India

    Oracle Soa12C Training From India

    Oracle Goldengate Training From India

    ResponderEliminar
  27. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage contribution from other ones on this subject while our own child is truly discovering a great deal. Have fun with the remaining portion of the year.

    Data science training in tambaram | Data Science training in anna nagar
    Data Science training in chennai | Data science training in Bangalore
    Data Science training in marathahalli | Data Science training in btm

    ResponderEliminar
  28. GOOD post! Thanks for SHARING a good stuff related to DevOps, Explination is good, nice Article
    anyone want to learn advance devops tools or devops online training
    DevOps Online Training
    DevOps Online Training hyderabad

    ResponderEliminar
  29. I accept there are numerous more pleasurable open doors ahead for people that took a gander at your site.we are providing ReactJs training in Chennai.
    For more details: ReactJs training in Velachery | ReactJs training in chennai

    ResponderEliminar
  30. Its really an Excellent post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog. Thanks for sharing....
    Microsoft Azure online training
    Selenium online training
    Java online training
    Java Script online training
    Share Point online training

    ResponderEliminar
  31. A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.
    Devops Training in Chennai | Devops Training Institute in Chennai

    ResponderEliminar
  32. Tanto spam por doquier en los comentarios xD

    ResponderEliminar
  33. Thank you for excellent article.You made an article that is interesting.
    AWS Solutions Architect courses in Bangalore with certifications.
    https://onlineidealab.com/aws-training-in-bangalore/

    ResponderEliminar
  34. keep up the good work. this is an Assam post. this to helpful, i have reading here all post. i am impressed. thank you. this is our digital marketing training center. This is an online certificate course
    digital marketing training in bangalore / https://www.excelr.com/digital-marketing-training-in-bangalore

    ResponderEliminar
  35. Nice blog,I understood the topic very clearly,And want to study more like this.
    Data Scientist Course

    ResponderEliminar
  36. Attend The Digital Marketing Courses in Bangalore From ExcelR. Practical Digital Marketing Courses in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Digital Marketing Courses in Bangalore.
    Digital Marketing Courses in Bangalore

    ResponderEliminar
  37. Attend The Data Science Courses Bangalore From ExcelR. Practical Data Science Courses Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Science Courses Bangalore.
    Data Science Courses Bangalore
    Data Science Interview Questions

    ResponderEliminar


  38. Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more.

    digital marketing courses

    ResponderEliminar
  39. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.

    best digital marketing course in mumbai

    ResponderEliminar
  40. I am impressed by the information that you have on this blog. It shows how well you understand this subject.

    data science course

    ResponderEliminar
  41. wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article resolved my all queries.
    Data Science Course

    ResponderEliminar
  42. Your blog provided us with valuable information to work with. Each & every tips of your post are awesome. Thanks a lot for sharing.
    AWS training in chennai | AWS training in annanagar | AWS training in omr | AWS training in porur | AWS training in tambaram | AWS training in velachery

    ResponderEliminar
  43. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

    Correlation vs Covariance

    ResponderEliminar
  44. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Correlation vs Covariance
    Simple linear regression

    ResponderEliminar
  45. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.

    Data Science In Banglore With Placements
    Data Science Course In Bangalore
    Data Science Training In Bangalore
    Best Data Science Courses In Bangalore
    Data Science Institute In Bangalore

    Thank you..

    ResponderEliminar
  46. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!

    Simple Linear Regression

    Correlation vs Covariance

    ResponderEliminar
  47. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Correlation vs Covariance
    Simple linear regression
    data science interview questions

    ResponderEliminar
  48. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.

    data science interview questions

    ResponderEliminar
  49. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.

    Simple Linear Regression

    Correlation vs covariance

    KNN Algorithm

    ResponderEliminar
  50. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.

    data science interview questions

    ResponderEliminar
  51. Amazing Article ! I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Simple Linear Regression
    Correlation vs covariance
    data science interview questions
    KNN Algorithm
    Logistic Regression explained

    ResponderEliminar
  52. I am looking for and I love to post a comment that "The content of your post is awesome" Great work!

    Simple Linear Regression

    Correlation vs Covariance

    ResponderEliminar
  53. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging.After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts likethis. https://www.3ritechnologies.com/course/aws-online-training/

    ResponderEliminar
  54. Attend The Data Analyst Course From ExcelR. Practical Data Analyst Course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analyst Course.
    Data Analyst Course

    ResponderEliminar
  55. Hola, soy estudiante. Necesito ayuda! ¿Cómo puedo hacer un arreglo multidimensional de 2 filas y 5 columnas con un total de 10 espacios para almacenar nombres?

    ResponderEliminar
  56. Sharing the same interest, Infycle feels so happy to share our detailed information about all these courses with you all! Do check them out
    oracle training in chennai & get to know everything you want to about software trainings.

    ResponderEliminar
  57. Worth reading! Our experts also have given detailed inputs about these trainings & courses! Presenting here for your reference. Do checkout Python Training In Chennai & enjoy learning more about it.

    ResponderEliminar
  58. Everything is unguarded with an exact explanation of the difficulties. It was truly instructive. Your site is very useful. Much obliged for sharing!
    tech news

    ResponderEliminar
  59. Incredible data. Fortunate me I went over your site by some coincidence (earthcycle). I've book-checked it for some other time!

    ResponderEliminar
  60. Hi! Thank you for the share this information. This is very useful information for online blog review readers. Keep it up such a nice posting like this.

    Data Science Training in Chennai

    Data Science Course in Chennai

    ResponderEliminar
  61. Thanks for posting the best information and the blog is very informative.Data science course in Faridabad

    ResponderEliminar
  62. Highly appreciable regarding the uniqueness of the content. This perhaps makes the readers feels excited to get stick to the subject. Certainly, the learners would thank the blogger to come up with the innovative content which keeps the readers to be up to date to stand by the competition. Once again nice blog keep it up and keep sharing the content as always.
    Data Science Training

    ResponderEliminar
  63. Searching for the Oracle DBA Training in Chennai? Then come to Infycle for the best software training in Chennai. Infycle Technologies is one of the best software training institute in Chennai, which offers various programs in Oracle such as Oracle PLSQL, Oracle DBA, etc., in complete hands-on practical training from professionals in the field. Along with that, the interviews will be arranged for the candidates and 200% placement assurance will be given here. To have the words above in your life, call 7502633633 to Infycle Technologies and grab a free demo to know more.Top Oracle DBA Training in Chennai

    ResponderEliminar
  64. Thanks for posting the best information and the blog is very helpful.data science interview questions and answers

    ResponderEliminar

Eres libre de realizar cualquier comentario, desde que pueda ayudar con gusto lo atenderé, y si es un critica, bienvenida sea!!!