help to use for loop in four layer

1 view (last 30 days)
hi
can enyone help me to write following code lines with use of for loops
p & ommega & v matrices are as follow:
v=zeros(6,3);
for i=1:3
v(4:end,i)=1+2*i;
end
ommega=zeros(6,3);
for i=1:3
ommega(4:end,i)=75+25*i;
end
p=zeros(6,3);
for i=1:3
p(4:end,i)=0.1*i;
end

Accepted Answer

Stephen23
Stephen23 on 5 Jul 2019
Edited: Stephen23 on 5 Jul 2019
Without loops:
>> [X,Y,Z] = ndgrid(1:3);
>> A = permute(cat(3,p(:,Z),ommega(:,Y),v(:,X)),[1,3,2]);
And checking with some examples:
>> [p(:,1),ommega(:,1),v(:,1)]
ans =
0 0 0
0 0 0
0 0 0
0.1 100 3
0.1 100 3
0.1 100 3
>> A(:,:,1)
ans =
0 0 0
0 0 0
0 0 0
0.1 100 3
0.1 100 3
0.1 100 3
>> [p(:,1),ommega(:,3),v(:,2)]
ans =
0 0 0
0 0 0
0 0 0
0.1 150 5
0.1 150 5
0.1 150 5
>> A(:,:,8)
ans =
0 0 0
0 0 0
0 0 0
0.1 150 5
0.1 150 5
0.1 150 5
>> [p(:,3),ommega(:,3),v(:,1)]
ans =
0 0 0
0 0 0
0 0 0
0.3 150 3
0.3 150 3
0.3 150 3
>> A(:,:,25)
ans =
0 0 0
0 0 0
0 0 0
0.3 150 3
0.3 150 3
0.3 150 3
  2 Comments
ali alipour
ali alipour on 5 Jul 2019
thank you very much
my problem was solved
but can do this with loops?
Stephen23
Stephen23 on 5 Jul 2019
Edited: Stephen23 on 5 Jul 2019
"but can do this with loops?"
Of course: preallocate A and then use indexing. You could generate the indices before the loop (e.g. using ndgrid) or inside the loop using division and modulo operations.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!