필터 지우기
필터 지우기

Creating matrix outside for loop

조회 수: 1 (최근 30일)
m13
m13 2017년 2월 19일
댓글: Star Strider 2017년 2월 20일
I need to create a matrix of variables and have the current code below. Is there anyway to do this without a for loop?
x = 0:.1:1;
y = 0:.1:1;
for i = 1:length(x)
for j = 1:length(y)
x2(i,j) = x(i);
y2(i,j) = y(j);
end
end

채택된 답변

Star Strider
Star Strider 2017년 2월 19일
편집: Star Strider 2017년 2월 19일
Try this:
x2 = y'*ones(size(x));
y2 = ones(size(y'))*x;
EDIT
The R2016b multiplication automatically does the expansion. Previous versions would require bsxfun calls:
x2 = bsxfun(@times, y', ones(size(x)));
y2 = bsxfun(@times, ones(size(y')), x);
  댓글 수: 5
m13
m13 2017년 2월 20일
Star if I need to use the y1 value in another for loop does this still work? I tried it and now I'm getting the error that the number of elements must be the same. The for loop is:
for k = 1:n
U(k) = sin(y1);
end
Star Strider
Star Strider 2017년 2월 20일
You do not need the loop.
This works:
U = sin(y1);
(I apologise for the delay.)

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

추가 답변 (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