How to fill 3D array using for loop with data z allocated to specific x and y values

3 次查看(过去 30 天)
Hi,
I want to create a logical 3D array with a 1 at each place where z (x,y) exists. My code is:
X=[0.5;0.5;0.6;0.6];
Y=[0.6;0.7;0.6;0.7];
V=[1.0794;1.1794;1.1646;1.2646];
A=zeros(length(X),length(Y),length(V));
for i=1:length(X)
for j=1:length(Y)
for k=1:length(V)
if i==j==k & V(k)>0
A(i,j,k)=1;
end
end
end
end
As you can see, the V values are already calculated and allocated to the varations of X and Y (first value of V belongs to 1st value of X and 1st value of Y, 2nd value of V belongs to 2nd values of X and Y, ...) So for i=1, j=1, k=1 there exists a value for V at the position k=i=j=1. At the position i=1, j=2, k=1 a wrong assignment arises, because in vector V at the position 1 there is of course a value. But this value does not belong to the combination of place 1 of vector X and place 2 of vector Y. My condition in the code does not work as I need it. I need as first condition that the correct position k of V is assigned to the corresponding positions i of X and j of Y. If the condition is met, the second condition checks if the value at location k in vector V is >0 and replaces the 0 at the location with a 1. Unfortunately there is no other way to display X and Y, because the data is calculated like this.
How can I write the first condition so that it works? At the moment I get the following array:
val(:,:,1) =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
val(:,:,2) =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
val(:,:,3) =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
val(:,:,4) =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
I suppose the answer is simple and I just don't see it at the moment. Thank you for your help!
  3 个评论
Walter Roberson
Walter Roberson 2021-5-8
if i==j==k & V(k)>0
A(i,j,k)=1;
end
If i must equal j and k then you can skip most of the loops:
for k=1:min([length(X), length(Y), length(V)])
if V(k) > 0
A(k,k,k) = 1;
end
end
which could be further vectorized.

请先登录,再进行评论。

采纳的回答

Matt J
Matt J 2021-5-8
编辑:Matt J 2021-5-8
X=[0.5;0.5;0.6;0.6];
Y=[0.6;0.7;0.6;0.7];
V=[1.0794;1.1794;1.1646;1.2646];
[I,J,K]=ndgrid(1:length(X), 1:length(Y), 1:length(V))
A = (I==J) & (J==K) & V(K)>0;

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by