How to fix "Subscripted assignment dimension mismatch" in For loop with min/sort functions, (or other)

1 次查看(过去 30 天)
In the following code F(:,i) is being assigned different column sizes for each iteration i. The Dmin sort was my attempt at taking the smallest 2 values (I only want 2 rows for all i in F composed of the min distance (x,y) locations in X), but for instance with [1 2], [0 1], and [1 0] in pts they are all equal distance from point i=1 in X (1,1). Is there a way with the find command (or other method) to only take 2 values for F?
clc
clear all
close all
x=[1 2 3 4 5 6 7 8 9 10];
y=[1 2 3 4 5 6 7 8 9 10];
X=[x y];
pts=[0 0
3 5
1 2
0 1
1 0];
for i=1:10
D = sqrt((x(i)-pts(:,1)).^2+(y(i)-pts(:,2)).^2);
sort_minD = sort(D);
Dmin(1:2,i) = sort_minD(1:2,1);
F(:,i) = find(D<=Dmin(2,i));
end

采纳的回答

Star Strider
Star Strider 2014-7-3
‘Is there a way with the find command (or other method) to only take 2 values for F?’
Yes. Change the find call to:
F(:,i) = find(D<=Dmin(2,i), 2);
Adding the ‘2’ as a second argument will return only two values from find. You can further specify whether these are the 'first' or 'last' two, depending on what you want to do. See the documentation on find for details. (This has been the behaviour of find for the last several MATLAB versions, but not always, so check the documentation for your version.)

更多回答(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