我想循环遍历3个数组的不同元素,并创建一个矩阵作为其值的函数。
我的a
向量范围为1到5,我的b
向量范围为1到5,我的x
向量范围为2到10,如下所示。然后对于来自a
和b
的特定值,使用等式y=a*x+b
,我希望得到的y
向量对应于存储在第1列中的x
值y
矩阵的向量。
之后,逐个更改a
和b
,我希望将不同y
的结果存储在y
矩阵的相应列中。我怎样才能实现这一目标?
这是我尝试过的代码:
function mathstrial
a = [1:1:5];
b = [1:1:5];
x = [2:2:10];
for e1 = a
for e2 = b
for e3 = x
y = e1*x+e2;
end
end
end
disp(y)
end
我希望结果是
y =
3 4 5 6 7 ..
5 6 7 8 9 ..
7 8 9 10 11 ..
9 10 11 12 13 ..
11 12 13 14 15 ..
...
答案 0 :(得分:2)
你可以在没有任何循环的情况下做到这一点 - 更多“MATLAB-esque”的做事方式。
true
您想要的结果:
% Your a and b, to get combinations as a 5x5 grid we use meshgrid
[a,b] = meshgrid(1:5, 1:5);
% We want to make a 5x5x5 3D matrix, where the 2D layers each use a different value
% for x, and the gridded a and b we just generated. Get the layered x:
x = repmat(reshape(2:2:10, 1, 1, []), 5, 5, 1);
% Now we want the corresponding layered a and b
a = repmat(a, 1, 1, 5); b = repmat(b, 1, 1, 5);
% Now calculate the result, ensuring we use element-wise multiplication .*
y = a.*x + b;
% Reshape to be a 2D array, collapsing the 3rd dimension
y = reshape(y(:,:).', [], 5, 1);
通过使用y =
[3, 4, 5, 6, 7
5, 6, 7, 8, 9
7, 8, 9, 10, 11
9, 10, 11, 12, 13
...
41, 42, 43, 44, 45
51, 52, 53, 54, 55]
代替5来获得合适的尺寸,您可以轻松地使其更通用。
答案 1 :(得分:0)
您可以在一个y
for loop
a = [1:1:5];
b = [1:1:5];
x = [2:2:10];
y = zeros(5,5,5);
for ct = 1:length(a)
y(:,:,ct) = (a(ct).*x)'+b;
end
第二维上b
,第三维上a
。
甚至在一条不可读的行中
y=repmat((a'.*x),[1,1,length(b)])+repmat(permute(b,[1,3,2]),[length(x),length(a),1])
第二个a
,第三个维度b
答案 2 :(得分:-2)
a = [1:1:5];
b = [1:1:5];
x = [2:2:10];
y = zeros(5,5,5);
for i = 1:5
for j = 1:5
for k =1:5
y(i,j,k) = i*x(k)+j
end
end
end
final_y = reshape(y, [5, 25])