Conditional equations with cell arrays.

조회 수: 10 (최근 30일)
Nickolai Martonick
Nickolai Martonick 2020년 11월 11일
댓글: Star Strider 2020년 11월 12일
I have two cell arrays as an example. One cell array has positive values, one array has negative values. The cell array with negative values also has zeros.
y = {0 0 0 -179.4 0 -179.3 -178.3 -173.2 -178.9 -179.6}
x = {173.5 169.4 177.5 172.8 169.8 166.6 179.2 178.0 169.7 174.5}
The values represent maximum degrees of movement. The y array is the maximum negative component (if there was one) and the x array is the minimum positive component. 180 (or zero) equals an upright torso and no range of motion. I need to find out the total range of motion. For example the total range of motion between the first values in each array is 6.5 (180 - 173.5). If there is a maximum negative value as with the fourth movement, the range of motion would be 7.8 ((180 - abs(y{4}) + (180 - x{4})). I want to write a statement that performs one equation if there is a zero (180 - 173.5) and another if there is not a zero ((180 - abs(y{4}) + (180 - x{4})) and creates a new cell array of values {1:10}. I have tried the below for loop with if else statement without success. If I put the value of the cell in the place of i, the correct value is displayed. Otherwise for i, I get a single value that is 5.4 and I don't know where it comes from. If I write the loop with ROM{i} then there is an error.
for i = 1:length(y);
if y{i} == 0
ROM = (180 - x{i});
elseif y{i} < 0
ROM = (180 - abs(y{i})) + (180 - x{i});
else
end
end
Help appreciated.

채택된 답변

Star Strider
Star Strider 2020년 11월 12일
In one line with ‘logical indexing’:
y = {0 0 0 -179.4 0 -179.3 -178.3 -173.2 -178.9 -179.6};
x = {173.5 169.4 177.5 172.8 169.8 166.6 179.2 178.0 169.7 174.5};
fcn = @(x,y) (180-[x{:}]).*([y{:}]==0) + ((180 - abs([y{:}])) + (180 - [x{:}])).*([y{:}]<0);
ROM = fcn(x,y)
producing:
ROM =
Columns 1 through 7
6.5 10.6 2.5 7.8 10.2 14.1 2.5
Columns 8 through 10
8.8 11.4 5.9
To use the loop, index ‘ROM’. The ‘logical indexing’ approach is faster and more efficient.
  댓글 수: 2
Nickolai Martonick
Nickolai Martonick 2020년 11월 12일
편집: Nickolai Martonick 2020년 11월 12일
Thank you! Could you tell me what the purpose of the @ symbol?
Star Strider
Star Strider 2020년 11월 12일
As always, my pleasure!
The ‘@’ creates a function handle, here specifically denoting an anonymous function.
See the documentation on Anonymous Fucntions and What Is a Function Handle? for details.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by