Matlab less than comparison

7 ビュー (過去 30 日間)
Robert Demyanovich
Robert Demyanovich 2021 年 6 月 20 日
コメント済み: Stephen23 2021 年 6 月 20 日
The Matlab documentation is confusing me.
I want to test each cell in a specific row of an array (cA). If that cell has a value that is less than a constant (NC), then change the cell value to the constant. Here's what I have:
if cA(i+1,:) <NC;
cA(i+1,:)=NC;
end;
Is this correct? I'm confused because the documentation says that the result of the "<" statement is just a logical vector (in this case) of 1 and 0 depending upon whether the comparison is true or false.
  1 件のコメント
Stephen23
Stephen23 2021 年 6 月 20 日
Although you asked about the le operator, by far the simplest and most efficient solution to your problem is actually this:
cA(i+1,:) = max(NC,cA(i+1,:))

サインインしてコメントする。

回答 (2 件)

Chunru
Chunru 2021 年 6 月 20 日
The correct way should be:
cA(i+1,:) = max(cA(i+1,:), NC);
or
idx = cA(i+1,:) <NC;
cA(i+1, idx)=NC;
  2 件のコメント
Walter Roberson
Walter Roberson 2021 年 6 月 20 日
is cA numeric or is it a cell array?
Robert Demyanovich
Robert Demyanovich 2021 年 6 月 20 日
I'm sorry. I don't understand. cA is an array of size MxN. The values in each cell or I guess MatLab calls it an element should always be a real number.

サインインしてコメントする。


Atsushi Ueno
Atsushi Ueno 2021 年 6 月 20 日
>Is this correct? ---> Yes, it is correct syntax. No, it does not behave as you expect.
cA = randi(10,[3 10]); i = 1; NC = 5; % temporary value
%if cA(i+1,:) < NC; % 1: No semi-colon, 2: any() is needed, 3: actually if statement is not needed
cA(i+1,cA(i+1,:)<NC) = NC % all of row i+1 of cA is set as NC
cA = 3×10
8 5 10 9 9 3 2 5 2 10 6 8 5 5 5 9 6 8 8 8 2 7 9 3 2 6 6 7 2 9
%end; % 1: No semi-colon, 3: actually if statement is not needed
Now you are trying the third indexing approach. Please check out it.
>In MATLAB®, there are three primary approaches to accessing array elements based on their location (index) in the array. These approaches are indexing by position, linear indexing, and logical indexing.
  • Indexing with Element Positions
  • Indexing with a Single Index
  • Indexing with Logical Values
> Expressions that include relational operators on arrays, such as A > 0, are true only when every element in the result is nonzero.
if statement is not needed in this question's case, but if you use if statement, you have to know that above specfication of if statement.

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by