Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Issues with basic Matlab command

  1. Sep 27, 2014 #1
    I need to figure out how to create a matrix that has zeros in everything except the diagonal, and I need the diagonal to be random numbers from 1 to 5. I tried a few different variations like this:

    R = eye(5)*7*randi(10,5)

    But I keep ending up with values in every row and column and I am at a loss as to why. I would think that multiplying the random by the identity matrix would clear out everything but the diagonal, but this code doesn't seem to be the right way to go about doing that. If anyone can help me out, I'd appreciate it.
  2. jcsd
  3. Sep 28, 2014 #2


    User Avatar
    Science Advisor
    Gold Member

    Do you know the difference, in Matlab, between * and .* ?
  4. Sep 28, 2014 #3
    Regretfully not. The only language I am at all familiar with is some C++. Matlab is completely new to me. Our instructor threw a project at us with Matlab and told us the instructions guided us through all of it, so knowledge of Matlab was not necessary. That was not even remotely the case and I have spent hours on end trying to figure out the convoluted instructions.

    It seems like finding this type of stuff out online is like finding a needle in a haystack. C++ resources have always been easy, but finding decent resources for Matlab just seems daunting.

    I tried to do a web search on .* and had no luck finding it. Can you tell me what it does?
  5. Sep 28, 2014 #4


    User Avatar
    Science Advisor
    Gold Member

    Last edited: Sep 28, 2014
  6. Sep 28, 2014 #5
    Oh, now I get it. Thank you so much for the information. I should be good now.
  7. Sep 29, 2014 #6


    User Avatar
    Gold Member

    Another way to do this is using the diag() function, which can do two things

    - Create a new diagonal matrix with the elements in the input vector on the main diagonal
    - Return the diagonal elements from an existing matri (default is the main diagonal, otherwise you use a number as the second input to specify).

    So for a 5x5 with random integers between 1 and 5 you could do,

    Code (Text):


    ans =

         5     0     0     0     0
         0     5     0     0     0
         0     0     1     0     0
         0     0     0     5     0
         0     0     0     0     4
    Or for random floats,

    Code (Text):

    r = 1 + 4*rand(5,1);
    ans =

        1.3902         0         0         0         0
             0    2.1140         0         0         0
             0         0    3.1875         0         0
             0         0         0    4.8300         0
             0         0         0         0    4.8596
    Hope this helps.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook