如果不在MATLAB中使用for循环,我怎么能知道如何替换特定矩阵位置的值?我初始化矩阵a,我想在每个指定的行和列上替换它的值no.这必须在numfor循环中进行一段时间.的num,因为我想在更新的原代码值循环是在这里非常重要的.
真正的代码更复杂,我正在简化这个问题的代码.
我的代码如下:
a = zeros(2,10,15);
for num = 1:10
b = [2 2 1 1 2 2 2 1 2 2 2 2 1 2 2];
c = [8.0268 5.5218 2.9893 5.7105 7.5969 7.5825 7.0740 4.6471 ...
6.3481 14.7424 13.5594 10.6562 7.3160 -4.4648 30.6280];
d = [1 1 1 2 1 1 1 1 1 1 3 1 6 1 1];
for no = 1:15
a(b(no),d(no),no) = c(1,no,:)
end
end
Run Code Online (Sandbox Code Playgroud)
示例输出13表示如下:
a(:,:,13) =
Columns 1 through 8
0 0 0 0 0 7.3160 0 0
0 0 0 0 0 0 0 0
Columns 9 through 10
0 0
0 0
Run Code Online (Sandbox Code Playgroud)
非常感谢你给我的任何帮助.
它可以使用sub2ind,将subs转换为线性索引.按照你的模糊变量名称,它看起来像这样(省略无用的循环num):
a = zeros(2,10,15);
b = [2 2 1 1 2 2 2 1 2 2 2 2 1 2 2];
d = [1 1 1 2 1 1 1 1 1 1 3 1 6 1 1];
c = [8.0268 5.5218 2.9893 5.7105 7.5969 7.5825 7.0740 4.6471 ...
6.3481 14.7424 13.5594 10.6562 7.3160 -4.4648 30.6280];
% // we vectorize the loop over no:
no = 1:15;
a(sub2ind(size(a), b, d, no)) = c;
Run Code Online (Sandbox Code Playgroud)