フィルターのクリア

Storing elements of product in a row matrix and extracting the nonzero elements

1 回表示 (過去 30 日間)
SM
SM 2022 年 5 月 30 日
コメント済み: Stephen23 2022 年 5 月 30 日
I have three row matrices x,y and z and I need to store the product of each element in a row matrix. For eg: x=[x1 x2 x3], y=[y1 y2 y3],z=[z1 z2 z3]. Then n is a matrix such that n=[x1*y1*z1 x1*y1*z2 x1*y1*z3 x1*y2*z1 x1*y2*z2 x1*y2*z3 ...x3*y3*z3]. And then I have to form a row matrix which should store only the nonzero elements of n. I am unable to do this using hte following code. Kindly help:
clc;
clear all;
x=[0 1 0];
y=[ 0.3333 0.6667 0];
z=[0.7667 0.2333 0];
for i=1:3
for j=1:3
for k=1:3
n=x(i).*y(j).*z(k);
n1=reshape(n',1,[])
end
end
end

回答 (2 件)

Johan
Johan 2022 年 5 月 30 日
The problem of your code is that you assign the results of your multiplaction to n, which mean that you will only store the last results of your for loop in n. To fix that you need to assign an array index to n(index) that increases after each loop cycle.
However, dot product directly multiplies matrices element-wise so you don't need for loops here:
a = [1 2 3];
b = [3 2 1];
a.*b
ans = 1×3
3 4 3
To extract nonzero element you can either use logical masking or the nonzeros function:
x=[0 1 0];
y=[ 0.3333 0.6667 0];
z=[0.7667 0.2333 0];
n=x.*y.*z
n = 1×3
0 0.1555 0
n_nozero=nonzeros(n)
n_nozero = 0.1555
  1 件のコメント
SM
SM 2022 年 5 月 30 日
Thanks for the input. I used for loops as I need to multiply each element of x with each elemnt of y and z. SO ultimately I need a 1x27 matrix consisting of all the product terms.

サインインしてコメントする。


Stephen23
Stephen23 2022 年 5 月 30 日
x = 1:3;
y = 4:6;
z = 7:9;
[X,Y,Z] = ndgrid(x,y,z);
A = nonzeros(X.*Y.*Z)
A = 27×1
28 56 84 35 70 105 42 84 126 32
  4 件のコメント
SM
SM 2022 年 5 月 30 日
Thanks alot! but I need the n matrix for some other operations apart from the A(nonzeros matrix)
Stephen23
Stephen23 2022 年 5 月 30 日
"but I need the n matrix for some other operations apart from the A(nonzeros matrix)"
There is nothing stopping you from keeping both of them:
N = X.*Y.*Z;
N = N(:); % optional
A = nonzeros(N).';

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by