开发者

Matlab - dynamic indexing

In matlab, do I have to declare a matrix, and how do I do it? For example, can I do

function res = compute()
  res(1) 开发者_开发问答= 1;
  res(2) = 2;
end

or do I have to declare res first?


You don't have to declare your matrices in matlab. Your code will work.

It is generally faster if you preallocate memory using ones or zeros for your matrices. Otherwise Matlab has to keep reallocating memory as the matrix changes size.

Example

% Slow
x(1) = 3; % x is now 1 by 1
x(5) = 9; % Matlab has to reallocate memory to increase x to be 1 by 5
x(10) = 2; % And another reallocation to increase x to be 1 by 10

% Better
y = zeros(1,10); % preallocate memory for the matrix
y(1) = 3;
y(5) = 9;
y(10) = 2;

% One-liner
z([1 5 10]) = [3 9 2]; % you can assign multiple values at once

Preallocation helps the most when you have to use loops

a = zeros(1,100)
for i=1:100
    a(i) = i^2;
end

Even better if you can vectorize code so you don't have to use a for loop

a = (1:100).^2;


Yes. There are many ways, you can start by first learning how to declare arrays here.

In your case, it looks like you are trying to do something like:

res = [1,2]


You don't have to declare the array/matrix. What you have right now will work.

You can always declare an empty matrix with matrix = []

Even crazier, you can do stuff like

a(2,3) = 7

resulting in

a =

     0     0     0
     0     0     7
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜