Calculate values only once in the loop

Suppose I have a code running in a loop I have done some operations and I create a matrix in the loop, that matrix has the same size in every iteration. How do i calculate the number of elemens of the matrix only for the first iteration and not for every iteration since i know that it will be the same for every iteration? I want to avoid using ifelse statements.

답변 (2개)

KSSV
KSSV 2018년 9월 12일

0 개 추천

Read about function numel. This will give you the number of elements present. Also you can get size of matrix and do product to get the elements.

댓글 수: 5

D_coder
D_coder 2018년 9월 12일
편집: D_coder 2018년 9월 12일
I already know that but in my case I want to calculate the number of elements only for the first iteration and avoid calculating the number of elements again and again inside the loop
for i = 1:N
if i == 1
N = numel(A) ;
end
end
KALYAN ACHARJYA
KALYAN ACHARJYA 2018년 9월 12일
편집: KALYAN ACHARJYA 2018년 9월 12일
@KSSV Sir, I also looking for the answer, I tried but didn't get the way
%If the condition is true, then only execute the statement
%How to avoid if statement in above code?
N(condition true)=execate the statement
N = 0 ; % number of elements
for i = 1:10
A = rand(10) ;
while ~N
N = numel(A) ;
end
end
D_coder
D_coder 2018년 9월 12일
is there anyother way to calculate without using loops or if else statement. How about N(N==0) = execute the statement

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

Amir Xz
Amir Xz 2018년 9월 12일

0 개 추천

Use "isempty":
I = rand(4,5);r=[]; c=[];
for i=1:10
if isempty(r) || isempty(c)
[r,c]=size(I);
end
end

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2018년 9월 12일

댓글:

2018년 9월 12일

Community Treasure Hunt

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

Start Hunting!

Translated by