Conditional equations with cell arrays.

6 次查看(过去 30 天)
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