-4

I want to create the following matrix in MATLAB:

M= [ 0 0 1 10 20
     0 0 3 8  26
     0 0 5 6  32
     0 0 0 0  0]

but I don't want to input all elements manually.

I tried M (1:3,3:5)=[x;y;z]

where

  • x is the linspace of 1 to 5
  • y is the linspace of 10 to 6
  • z is the linspace of 20 to 32

but it doesn't work (the last row of zeros is missing). How can I create M in a smart way?

jub0bs
  • 60,866
  • 25
  • 183
  • 186
Litmus Tang
  • 1
  • 1
  • 2

3 Answers3

0

I'm assuming that this is some programming assignment, because otherwise I don't see a reason why this needs to be done in a single line. I'm also assuming that concatenating a vector of zeros is unwanted. Having said that here are several suggestions:

Suppose that your vectors are defined like so:

x = 1:2:5;
y = 10:-2:6;
z = 20:6:32;

The "cleanest" way (under the assumption of no-zero-vector-concatenation) is probably:

M = subsasgn(zeros(4,5),substruct('()',{1:3,3:5}),[x',y',z']);

Alternatively, if using external functions, you can use the insertrows submission on FEX:

M = insertrows(insertrows([(x)',(y)',(z)'],0,4)',0,[0,0])';

With two commands, and assuming that M doesn't exist, you can do:

M(2:4,3:5)=([fliplr(x)',fliplr(y)',fliplr(z)']);
M = flipud(M);
Dev-iL
  • 23,742
  • 7
  • 57
  • 99
0

Strange question, but here you go, in one command. This assumes M is previously non-existent, and that x, y and z are defined as x = 1:2:5; y = 10:-2:6; z = 20:6:36;:

M(1:4,3:5) = [[x;y;z].'; zeros(1,3)];

You can of course avoid x, y and z by defining their values on the fly:

M(1:4,3:5) = [[1:2:5; 10:-2:6; 20:6:36].'; zeros(1,3)];
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0

If you are looking for one-liner that requires no other input(s) and creates the linspace values internally, here's one -

M(1:4,3:5)=[bsxfun(@plus,[1 10 20],bsxfun(@times,[2 -2 6],[0:2]'));zeros(1,3)]

Output -

M =
     0     0     1    10    20
     0     0     3     8    26
     0     0     5     6    32
     0     0     0     0     0
Divakar
  • 218,885
  • 19
  • 262
  • 358