How do I combine two cell arrays to form pairs that I can later calculate the distances between; one array contains my X Coordinates and the other contains my Y Coordinates.
4 次查看(过去 30 天)
显示 更早的评论
I have two cell arrays: X_Coordinates and Y_Coordinates
I would like to combine the two cell arrays to form pairs and then calculate the distance between each of those pairs.
I am a beginner at MATLAB, I would appreciate some help. Here is what I have so far but I do not know how to turn them into pairs (x, y) which I can use later in my code to calculate the distance between each other.
F.Y.I. Pdist did not work with me, instead it generated an enormous 19000x1 double array for some reason when I passed XY_Coordinates into it and used the euclidean method.
clc;
close all;
clearvars;
numOfNodes = 10;
% randi(K, M, N)
% K -> Generate random numbers from 1 to K
% M -> Number of rows in your cell array
% N -> Number of columns in your cell array
X_Values = randi(50, 200, 1); % Generate 200 (200x1 matrix) random numbers from 1 to 50.
Y_Values = randi(50, 200, 1);
XY_Coordinates = [X_Values Y_Values];
0 个评论
回答(1 个)
Fifteen12
2022-12-1
Your question doesn't use cell arrays (those are for holding objects with arbitrary type), but if in your actual code you are using cell arrays, trying using the cell2mat function to convert them to numeric arrays.
With the code you've provided, you can find the 1D distance just by subtracting the two vectors:
X_Values = randi(50, 200, 1);
Y_Values = randi(50, 200, 1);
distance = Y_Values - X_Values;
If you want to find the consecutive distances between each pair then I'm guessing you might just have the wrong directions. Try:
X_Values = randi(50, 200, 1);
Y_Values = randi(50, 200, 1);
distance = pdist([X_Values', Y_Values']);
2 个评论
Fifteen12
2022-12-2
Good questions about some confusing terminology! This is a cell array in MATLAB:
a = cell(1, 3)
With cell arrays you can add any type of object to them:
a{1} = [1, 2, 3];
a{2} = [1, 2; 3, 4; 5, 6];
a{3} = 'A string even!';
disp(a)
Cell arrays are accessed and crated with {} curly brackets, while normal numerical arrays are created and accessed with [] square brackets. You can think of arrays as matrices (as long as they're 2D). But normal arrays don't have "cells" in the way you're using the word, they have entries I guess. Cells are as defined above. You can read more about cell arrays here and creating numerical arrays here.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!