필터 지우기
필터 지우기

Assigning values to an array using elements of another array after each element goes through a check

조회 수: 6 (최근 30일)
Hello,
Let's say that i have an array (e.g zeros(5,5)).
I'd like to use each element my array has, put each element through an if statement check, make some calculations, and assign that new value to another array that has the same dimensions as my initial one.
If anybody has any idea i'd be of great help!
Thanks!:)

채택된 답변

YT
YT 2017년 12월 14일
편집: YT 2017년 12월 14일
I think your looking for something like this
start_matrix = rand(5,5); %rand 5x5, values between 0 and 1 (cause whats the point in comparing zeros)
end_matrix = zeros(size(start_matrix)); %same size as starting matrix
for i = 1:size(start_matrix,1)
for j = 1:size(start_matrix,2)
if (start_matrix(i,j) > 0.5)
end_matrix(i,j) = start_matrix(i,j) * 666; %some crazy calculations
else
end_matrix(i,j) = start_matrix(i,j); %no crazy calculations if <= 0.5
end
end
end
end_matrix

추가 답변 (1개)

Matt J
Matt J 2017년 12월 14일
편집: Matt J 2017년 12월 14일
I'd like to use each element my array has, put each element through an if statement check
Just be aware that that's normally the kind of thing you try to avoid in MATLAB. For instance, YT's example is much more efficiently implemented as follows for large matrices,
condition = start_matrix>0.5;
end_matrix=start_matrix;
end_matrix(condition)=start_matrix(condition)*666;
  댓글 수: 2
YT
YT 2017년 12월 14일
I agree to what you said, but I think it's useful for beginners to understand how looping through a matrix works.
Matt J
Matt J 2017년 12월 14일
편집: Matt J 2017년 12월 14일
Yes, I know. I just want the OP to be aware of important alternatives.

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

카테고리

Help CenterFile Exchange에서 Matrix and Vector Construction에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by