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

조회 수: 12 (최근 30일)
翔 池田
翔 池田 2022년 2월 14일
댓글: Atsushi Ueno 2022년 2월 15일
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
Atsushi Ueno
Atsushi Ueno 2022년 2월 15일
表題:「非ゼロ要素の算出方法」
本文:「「1」を持つ値の座標(x,y,z)を算出する方法」
1を持つ値と非ゼロ要素は1対1の関係ではありません。
2を持つ値も3をもつ値も非ゼロ要素です。

댓글을 달려면 로그인하십시오.

답변 (1개)

Atsushi Ueno
Atsushi Ueno 2022년 2월 14일
下記のコマンドで「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

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!