How to create 3d array whose value follows a certain pattern without using for-loop?
조회 수: 10 (최근 30일)
이전 댓글 표시
How to create 3d array whose value follows a certain pattern without using for-loop?
For the following example, how to modify it to meet the requirement above?
A = zeros(m, n, 3);
for i = 1 : m
for j = 1 : n
A(i, j) = [i, j, i*j];
end
end
댓글 수: 0
답변 (1개)
Dyuman Joshi
2023년 9월 25일
편집: Dyuman Joshi
2023년 9월 25일
Your code will not run as you are trying to store 3 numeric values in 1 numeric place holder. I have corrected the code below
%Random values for example
m = randi(10)
n = randi(10)
A = zeros(m, n, 3);
for i = 1 : m
for j = 1 : n
%Correction
% v
A(i, j, :) = [i, j, i*j];
end
end
To get the same result without the for loop, utilize vectorization -
[M,N] = ndgrid(1:m,1:n);
%Concatenate individual arrays to make a 3D array
A0 = cat(3,M,N,M.*N);
%Check if the arrays are equal or not
isequal(A0,A)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!