Find elemet which are satisfy given condition

조회 수: 1 (최근 30일)
Mariia
Mariia 2023년 3월 14일
편집: Dyuman Joshi 2023년 3월 14일
hello to everyone! I have a task, where i need to find in column (x) with 100 numbers, such values which are less or equal than 400. And write all these values in new created matrix x1. When I run this code - new matrix from zeros is created, but it doesn't contain any numbers. What could be the reason? Will appreciate your help!
x1=zeros(100,1);
for i=1:100
if x(i)<=400
x1(i)=x(i);
end
end
  댓글 수: 1
Dyuman Joshi
Dyuman Joshi 2023년 3월 14일
편집: Dyuman Joshi 2023년 3월 14일
Your code looks good. What is the value of variable x?
You can assign the values via indexing, which is more efficient than loop
x = randi(750,10,1)
x = 10×1
386 629 86 13 279 497 411 409 239 458
x1 = zeros(size(x));
idx = x<=400;
x1(idx) = x(idx)
x1 = 10×1
386 0 86 13 279 0 0 0 239 0

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

채택된 답변

Jan
Jan 2023년 3월 14일
Your code is working:
x = [1, 401, 400, 500, 10, 300];
x1 = zeros(numel(x), 1);
for i = 1:numel(x)
if x(i) <= 400
x1(i) = x(i);
end
end
x1.'
ans = 1×6
1 0 400 0 10 300
You can omit the zeros also:
x = [1, 401, 400, 500, 10, 300];
x1 = zeros(numel(x), 1);
k = 0; % Another counter
for i = 1:numel(x)
if x(i) <= 400
k = k + 1;
x1(k) = x(i);
end
end
x1 = x1(1:k); % Crop unused elements
A more Matlab'ish way is to omit the loop:
x1 = x(x <= 400) % Logical indexing

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by