我有一個長度不同的矩陣陣列。我想比較矩陣 1 中每個專案與矩陣 2 中專案的距離,依此類推。我在下面撰寫的 for 回圈運行良好,除非它到達長度為 2 的矩陣。回圈繼續到 xx = 3,然后呼叫錯誤(“位置 1 的索引超出陣列邊界。索引不得超過 2。” ) 因為沒有 current_mat(3,:)。為什么只對長度為 2 的矩陣執行此操作?我對matlab比較陌生,所以如果這是一個簡單的問題,我深表歉意。以下是一些玩具資料,它們給出了與我在更大資料集上看到的相同的錯誤。
matrix_1 = ones(16,3)
matrix_2 = ones(14,3)
matrix_3 = ones(2,3)
matrix_4 = ones(10,3)
my_array = {matrix_1; matrix_2; matrix_3; matrix_4}
for ii = 1:length(my_array)-1;
current_mat = my_array{ii};
compare_mat = my_array{ii 1};
for xx = 1:length(current_mat);
xx_info = current_mat(xx,:);
end
end
uj5u.com熱心網友回復:
問題是當給定矩陣輸入時,length回傳矩陣的最長維度,而不是行數。在您的情況下matrix_3this 是 3,盡管您似乎期望 2。所以xx從 1 到 3 并且在第 11 行中,您嘗試訪問在 時不存在的行xx=3。更好的辦法是顯式地遍歷m維度。您可以使用size它回傳矩陣中的行數和列數:
matrix_1 = ones(16,3)
matrix_2 = ones(14,3)
matrix_3 = ones(2,3)
matrix_4 = ones(10,3)
my_array = {matrix_1; matrix_2; matrix_3; matrix_4}
for ii = 1:length(my_array)-1;
current_mat = my_array{ii};
compare_mat = my_array{ii 1};
[m,n] = size(current_mat); % <-- use size here, not length
for xx = 1:m;
xx_info = current_mat(xx,:);
end
end
或者,如果您想查看列:
matrix_1 = ones(16,3)
matrix_2 = ones(14,3)
matrix_3 = ones(2,3)
matrix_4 = ones(10,3)
my_array = {matrix_1; matrix_2; matrix_3; matrix_4}
for ii = 1:length(my_array)-1;
current_mat = my_array{ii};
compare_mat = my_array{ii 1};
[m,n] = size(current_mat); % <-- use size here, not length
for xx = 1:n;
xx_info = current_mat(:,xx);
end
end
uj5u.com熱心網友回復:
這段代碼應該適合你。您沒有具體指定列(或行)的長度作為決定因素,
matrix_1 = ones(16,3);
matrix_2 = ones(14,3);
matrix_3 = ones(2,3);
matrix_4 = ones(10,3);
my_array = {matrix_1; matrix_2; matrix_3; matrix_4};
for ii = 1:length(my_array)-1
current_mat = my_array{ii};
compare_mat = my_array{ii 1};
for xx = 1:size(current_mat,2) % length of columns
xx_info = current_mat(:,xx); % Can compare across columns, since no of columns are consistent across multiple matrices
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/410397.html
標籤:
上一篇:如何在matlab中將20個名字的串列隨機分配到4組而不重復
下一篇:如何將均勻分布擬合到直方圖?
