フィルターのクリア

How to multiply vectors not the same size to create 3d tensor?

6 ビュー (過去 30 日間)
Noya Linder
Noya Linder 2023 年 7 月 23 日
コメント済み: Voss 2023 年 8 月 15 日
Hi! I have a function that receives a few scalars along with a few vectors that calculates a certain value. I use the following for loop in order to fill in a 3D tensor that contains all results from all possible combinations of these three vectors:
Z3 = zeros(length(T), length(Rtry), length(theta));
x = 0;
y = 0;
z = 0;
for tt = t_obs
x = x+1;
y = 0;
for rr = Rtry
y = y+1;
z = 0;
for mm = mu
z = z + 1;
Z3(x, y, z) = toint(3, Rtry(y), t_obs(x), RT1, t_obs, dRdtT1, mu(z));
end
end
end
I want to vectorize this code but I'm having some trouble understanding how. I wrote this line
Ztry = toint(3, Rtry, t_obs, RT1, t_obs, dRdtT1, mu);
but I get the following error
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the
number of rows in the second matrix. To operate on each element of the matrix individually, use TIMES (.*) for
elementwise multiplication.
that occures in the following function:
function getTime = getShockFrameTime(t, r, mu)
c = 29979245800; %cm/s
getTime = t + r*mu/c;
end
with t, r and mu being the vectors t_obs, Rtry and mu, respectively.
The vectors are different lengths and I want it to return a 3D tensor, not a vector.
Thank you in advance :)

回答 (1 件)

Voss
Voss 2023 年 7 月 23 日
編集済み: Voss 2023 年 7 月 23 日
One thing you can do is reshape your vectors as desired and use .*, for example:
t_obs = [1 2 3]*1e-6;
Rtry = [4 5 6 7]*1e2;
mu = [8 9];
result = getShockFrameTime(t_obs, Rtry, mu);
size(result)
ans = 1×3
3 4 2
disp(result)
(:,:,1) = 1.0e-05 * 0.1107 0.1133 0.1160 0.1187 0.2107 0.2133 0.2160 0.2187 0.3107 0.3133 0.3160 0.3187 (:,:,2) = 1.0e-05 * 0.1120 0.1150 0.1180 0.1210 0.2120 0.2150 0.2180 0.2210 0.3120 0.3150 0.3180 0.3210
function getTime = getShockFrameTime(t, r, mu)
c = 29979245800; %cm/s
getTime = reshape(t,[],1) + reshape(r,1,[]).*reshape(mu,1,1,[])/c;
% reshaping like this, size(getTime) is [numel(t) numel(r) numel(mu)]
% adjust as necessary
end

カテゴリ

Help Center および File ExchangeOperators and Elementary Operations についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by