多次元行列での非ゼロ要素の算出方法

ns=5;
A=zeros(ns,ns,ns);
for dim=1:ns
n1=randi([1 ns],1,1);
n2=randi([1 ns],1,1);
n3=randi([1 ns],1,1);
A(n1,n2,n3)=1;
end
上記によって算出される変数Aにおいて,
「1」を持つ値の座標(x,y,z)を算出する方法を教えて頂きたいです.
for文を用いずに算出したいです.
宜しくお願い致します.

1 commentaire

Atsushi Ueno
Atsushi Ueno le 15 Fév 2022
表題:「非ゼロ要素の算出方法」
本文:「「1」を持つ値の座標(x,y,z)を算出する方法」
1を持つ値と非ゼロ要素は1対1の関係ではありません。
2を持つ値も3をもつ値も非ゼロ要素です。

Connectez-vous pour commenter.

Réponses (1)

Atsushi Ueno
Atsushi Ueno le 14 Fév 2022

1 vote

下記のコマンドで「1」を持つ値の座標(x,y,z)を算出出来ます。find関数の出力は線形インデックスなのでind2sub関数で3次元の添え字に変換します。2次元行列が対象の場合ind2sub関数は不要です。
[x,y,z] = ind2sub(size(A),find(A == 1));
ns=5;
A=zeros(ns,ns,ns);
for dim=1:ns
n1=randi([1 ns],1,1);
n2=randi([1 ns],1,1);
n3=randi([1 ns],1,1);
A(n1,n2,n3)=1;
[n1,n2,n3] % 1を設定した座標を表示する
end
ans = 1×3
2 1 4
ans = 1×3
5 5 2
ans = 1×3
2 5 4
ans = 1×3
5 3 2
ans = 1×3
5 5 1
[x,y,z] = ind2sub(size(A),find(A == 1)); % 「1」を持つ値の座標(x,y,z)を算出
[x y z]
ans = 5×3
5 5 1 5 3 2 5 5 2 2 1 4 2 5 4

Catégories

En savoir plus sur スパース行列 dans Centre d'aide et File Exchange

Tags

Question posée :

le 14 Fév 2022

Commenté :

le 15 Fév 2022

Community Treasure Hunt

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

Start Hunting!