Can a for statment contain a matrix

조회 수: 1 (최근 30일)
Ezekiel Willmott
Ezekiel Willmott 2022년 4월 30일
답변: Riccardo Scorretti 2022년 4월 30일
Im trying to filter the data in a matrix, for all values greater then 2.2 I want to know the difference between them and 3.3
This is what have written
for Ns1 >= 2.2
Ns1 = (Ns1-3.3)
end
Ns1 is a 200x1 matrix, I believe this to be the problem, but I haven't been able to find a soloution
Cheers and thankyou.

채택된 답변

Riccardo Scorretti
Riccardo Scorretti 2022년 4월 30일
The problem is formulated in a somehow unclear way. However, assume that we have a 200x1 matrix:
% Generate some random data, for sake of clarity
data = 5*rand(200, 1);
plot(data) ; hold on
A first approach consists in using find. In this way you will compute the difference between the found elements and 3.3 for elements which are greater than 2.2 only. This means that the size of Ns1 will not be necessarily equal to the size of the original data (most likely, it will be smaller), and Ns1 will be linked to data(ind):
ind = find(data > 2.2) ; plot(ind, data(ind), 'ro');
Ns1 = data(ind) - 3.3;
size(Ns1)
ans = 1×2
118 1
Another possibility would be to compute Ns1 for all elements - whatever their value - and set to 0 or to NaN the value for the elements which are smaller or equal to 2.2. In this way the size of Ns1 and of the original matrix will be the same, and Ns1 will be linked directly to data:
Ns1 = data - 3.3;
Ns1(data <= 2.2) = NaN; % or 0, as you prefer
size(Ns1)
ans = 1×2
200 1

추가 답변 (1개)

Walter Roberson
Walter Roberson 2022년 4월 30일
For vector Ns1:
mask = Ns1 >= 2.2;
Ns1diff = Ns1(mask) - 3.3;
But is that useful? The Ns1diff variable here just contains information for the entries that were >= 2.2, and does not contain any information about where those entries occurred.
Your code (but not your description) hints you might want to subtract 3.3 from each entry that is >= 2.2. If so that is not a problem:
mask = Ns1 >= 2.2;
Ns1(mask) = Ns1(mask) - 3.3;

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by