2011-07-26 61 views
0

在matlab中,我必須聲明一個矩陣,我該怎麼做?例如,我能做Matlab - 動態索引

function res = compute() 
    res(1) = 1; 
    res(2) = 2; 
end 

還是我必須首先聲明res?

回答

1

是的。有很多方法,你可以先從學習如何聲明數組here開始。

在你的情況下,它看起來像你正在嘗試做的是這樣的:

res = [1,2]

1

您不必聲明數組/矩陣。你現在所擁有的將會起作用。

您可以隨時與聲明matrix = []

甚至更​​瘋狂的空矩陣,你可以做的東西一樣

a(2,3) = 7 

導致

a = 

    0  0  0 
    0  0  7 
2

你不必申報您的矩陣在matlab中。你的代碼將起作用。

如果您使用oneszeros爲您的矩陣預分配內存,速度通常更快。否則,當矩陣改變大小時,Matlab必須繼續重新分配內存。

% 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 

預分配有助於最時,你必須使用循環

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

更妙的是,如果你能向量化的代碼,這樣你就不必使用for循環

a = (1:100).^2;