For Loop runs too many times

조회 수: 6 (최근 30일)
Tico
Tico . 2012년 12월 8일
Hi everyone.. I'm new to matlab and am trying to populate a 3D array by the results of a loop:
for j=1:4
A=randi([0 1],2,3);
C(:,:,j)=A
end
And I am getting different 2x3 C matrices where j=1, 2, then j=1,2,3 then j=1,2,3,4. Is there a way I can run the loop just for j=1, then j=2, thenj=3 and j=4? I thought I should be getting a 3D array containing just 4 "pages" (i-e, 4 matrices??
Thnx..

답변 (2개)

Matt Fig
Matt Fig 2012년 12월 9일
편집: Matt Fig 님. 2012년 12월 9일
I am confused about your question. You say you want to have C be a 2-by-3-by-4 array at the end of the loop, correct? That is exactly what you have at the end of your loop!
>> clear all
for jj = 1:4
A=randi([0 1],2,3);
C(:,:,jj)=A; % Semicolon!!
end
whos C % This tells us what we have in C.
Name Size Bytes Class Attributes
C 2x3x4 192 double
Notice that C is the exact size you want. I wonder if you got confused by leaving off the semicolon so that while the loop was running and so you saw C being built-up for every iteration? This is just one reason to not forget to put a semicolon on your lines of code! There is no practical reason to watch all that screen-dump!
Also, why not just do:
C = randi([0 1],2,3,4); % No loop needed...
  댓글 수: 2
Matt Fig
Matt Fig 2012년 12월 9일
편집: Matt Fig 님. 2012년 12월 9일
Exactly! Did you read what I wrote??? Those outputs are you seeing the array being built up during the loop, not the final array. Put a semicolon on there (or copy and paste the code I gave you) and you will not see that awful mess any more....
Slow down and read what was written!

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


Azzi Abdelmalek
Azzi Abdelmalek 2012년 12월 8일
편집: Azzi Abdelmalek 님. 2012년 12월 9일
C=zeros(2,3,4) % preallocate makes your code faster
for jj=1:4
A=randi([0 1],2,3);
C(:,:,jj)=A
end
The result is one matrix 2x3x4
% avoid using i or j (used to represent imaginary numbers)
  댓글 수: 2
Azzi Abdelmalek
Azzi Abdelmalek 2012년 12월 9일
편집: Azzi Abdelmalek 님. 2012년 12월 9일
do you want
clear
k=0;
for j=1:4:4
k=k+1
A=randi([0 1],2,3);
C(:,:,k)=A
end
but for k=1:4:4 gives you just k=1

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

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by