For Loop /Array question

조회 수: 1 (최근 30일)
Tyler Young
Tyler Young 2020년 2월 3일
댓글: Tyler Young 2020년 2월 4일
How would i go about creating a for loop to create an array where each value in X is equal to its associated row value * 2 plus its associated column value * 3 +1. Size of array is 50x50 ?
  댓글 수: 2
James Tursa
James Tursa 2020년 2월 3일
What have you done so far? What specific problems are you having with your code? Do you know how to write a for-loop? Do you know how to pre-allocate a 50x50 matrix?
Tyler Young
Tyler Young 2020년 2월 4일
I know how to write simpler for loops where I can identify a "start" point for my indx and run through a simple array or vector to "end" but Im struggling to comprehend how to build the value of this equation.

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

채택된 답변

Hiro Yoshino
Hiro Yoshino 2020년 2월 4일
How about this?:
X = zeros(50, 50);
[m, n] = size(X); % m x n = 50, 50
for i = 1:m % Row
for j = 1:n % Column
X(i, j) = i * 2 + j * 3 + 1;
end
end
(m, n) could be anytihng.
The point here is size function. Good luck!
  댓글 수: 1
Tyler Young
Tyler Young 2020년 2월 4일
Thank you, that does work, and helps to see it done that way too. I ended up going about it differently, but I was orginally thinking of using "zeros"
for row = 1:1:50
for col = 1:1:50
X(row,col) = [row * 2 + col * 3 + 1]
end
end

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

추가 답변 (1개)

KSSV
KSSV 2020년 2월 4일
Check the below deom code where each element of a matrix is sum of its row and column position. Extend this to your case.
m = 5 ; % number of rows
n = 5 ; % number of columns
iwant = zeros(m,n) ; % initialize the required matrix
% loop
for i = 1:m % loop for row
for j = 1:n % loop for column
iwant(i,j) = i+j ; %(i,j)th element is sum of i and j
end
end
  댓글 수: 1
Tyler Young
Tyler Young 2020년 2월 4일
Thank you, appreciate the multiple ways of seeing this done.

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

카테고리

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