我會做一些假設:
- 你想返回值是
q
爲在函數簽名中,並且
你想在你的樣本情況下的輸出是一個10x5矩陣,像這樣:
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
固定循環
給出錯誤的問題是,你將10x1
載體ZERO
分配給5x1
載體的單個(標量)元件y
:
y(i) = ZERO;
一個向量不適合標量。但是,即使您將此更改爲將ZERO
分配給y
列,也不適合,因爲列的長度不同。這不是你想要做的,因爲如果它有效的話,你可能只會抹去y
中的值。所以讓我們設置輸出數組q
的列中的值。變動(標有註釋<==
。)
function q = convert
% Convert y matrix values to 10xn matrix
%load('y.mat');
y = [1; 2; 3; 4; 5]; % <== replace load temporarily
% Set 10x1 Matrix of zeros
ZERO = zeros(10,1);
% Preallocate output array
q = zeros(10, length(y)); % <== preallocate for speed
for i = 1:length(y)
ZERO(y(i)) = 1; % Set yth element of ZERO to 1
q(:,i) = ZERO; % <== Set ith *column* of *q* equal to new zero
ZERO = zeros(10,1); % Re-establish zero
endfor
改善循環
這將工作,但如果你預先分配q
,你已經得到的ZERO
正確的號碼向量,爲什麼不直接設置值?
function q = convert
% Convert y matrix values to 10xn matrix
%load('y.mat');
y = [1; 2; 3; 4; 5]; % <== replace load temporarily
% Preallocate output array
q = zeros(10, length(y)); % <== preallocate for speed
for i = 1:length(y)
q(y(i),i) = 1; % <== Set element at y(ith) row and ith column of q to 1
endfor
查殺環
這兩種循環會給你想要的結果,但你可以做到這整個操作沒有環。This answer總結了不同的方式來做到這一點,但我只告訴你使用sub2ind
第一個:
function q = convert
% Convert y matrix values to 10xn matrix
%load('y.mat');
y = [1; 2; 3; 4; 5]; % <== replace load temporarily
% Preallocate output array
q = zeros(10, length(y)); % <== preallocate for speed
idx = sub2ind(size(q), y, [1:length(y)].');
q(idx) = 1;
最後說明
最好不要使用i
作爲一個變量名八度/ MATLAB。這在其他語言中很自然,但在MATLAB i
(或j
)中是imaginary unit。如果您使用i
作爲變量,它會隱藏該常數。如果您在分配複雜值時使用1i
(或1j
),但這不會產生影響,但您必須記住這樣做,並且在某些時候您將忘記。
你能給我們一些樣本輸入和相應的預期輸出嗎? – beaker
y = [1; 2; 3; 4; 5]輸入並且y = [[1; 0; 0; 0; 0; 0; 0; 0; 0; 0]; [0; 1; 0; 0; 0; 0; 0; 0; 0; 0] ; [0; 0; 1; 0; 0; 0; 0; 0; 0; 0]; [0; 0; 0; 0; 1; 0; 0; 0; 0; 0]; [0; 0; 0; 0; 0; 1; 0; 0; 0; 0]輸出。我通過在需要的地方按元素執行轉換元素來解決這個問題。我只是希望能像這一樣一步到位。 –