Getting array from struct array in Matlab without loops - arrays

I have a binary image with some objects, and I want to get some characteristics of these objects.
I = imread('coins.png');
B = im2bw(I, 100/255); B = imfill(B, 'holes');
RP = regionprops(B, 'Area', 'Centroid');
RP becomes a structure array:
10x1 struct array with fields:
Area
Centroid
I need to make from this structure 2 arrays called Areas and Centroids.
How to make it without loops?
Using loops we can go this way:
N = numel(RP);
Areas = zeros(N, 1); Centroids = zeros(N, 2);
for idx=1:N,
Areas(idx) = RP(idx).Area;
Centroids(idx, :) = RP(idx).Centroid;
end

You can simply concat
Areas = [RP.Area];
Centroids = vertcat( RP.Centroid );
PS,
It is best not to use i as a variable name in Matlab.

Related

How to find the intersection between two MATLAB tall arrays?

In common arrays the intersection function would have worked great, but for tall arrays this function has not been implemented yet. So is there an other way to find the common elements of these two?
Use a for-loop to do the checks
n = 1e4;
m = 1e3; %Batchsize
a = tall(randi(n,n,1));
b = tall(randi(n,1,n));
idx = tall(false(n,1));
for ii = 1:n/m
idx = idx | any(a==b(1,(ii-1)*m+1:ii*m),2);
end
inter = a(idx);
Where m controls how much of the array you can load into the memory at the time. The more the faster, but you will need to have enough memory for it.

How to return the leaves of a struct as vector in Matlab?

Often I need to access the leaves of data in a structured array for calculations.
How is this best done in Matlab 2017b?
% Minimal working example:
egg(1).weight = 30;
egg(2).weight = 33;
egg(3).weight = 34;
someeggs = mean([egg.weight]) % works fine
apple(1).properties.weight = 300;
apple(2).properties.weight = 330;
apple(3).properties.weight = 340;
someapples = mean([apple.properties.weight]) %fails
weights = [apple.properties.weight] %fails too
% Expected one output from a curly brace or dot indexing expression,
% but there were 3 results.
If only the top level is a non-scalar structure array, and every entry below is a scalar structure, you can collect the leaves with a call to arrayfun, then do your calculation on the returned vector:
>> weights = arrayfun(#(s) s.properties.weight, apple) % To get the vector
weights =
300 330 340
>> someapples = mean(arrayfun(#(s) s.properties.weight, apple))
someapples =
323.3333
The reason [apple.properties.weight] fails is because dot indexing returns a comma-separated list of structures for apple.properties. You would need to collect this list into a new structure array, then apply dot indexing to that for the next field weight.
You can collect properties into a temporary structure array, and then use it as normal:
apple_properties = [apple.properties];
someapples = mean([apple_properties.weight]) %works
This wouldn't work if you had even more nested levels. Perhaps something like this:
apple(1).properties.imperial.weight = 10;
apple(2).properties.imperial.weight = 15;
apple(3).properties.imperial.weight = 18;
apple(1).properties.metric.weight = 4;
apple(2).properties.metric.weight = 7;
apple(3).properties.metric.weight = 8;
Not that I would advise such a structure, but it works as a toy example. In that case you could, do the same as the previous in two steps... or you could use arrayfun.
weights = arrayfun(#(x) x.properties.metric.weight, apple);
mean(weights)

Pythonic way in matlab to decompose array to variables

So I want to decompose array to multiple variables.
For example,
I have 'data' array of (136,9) size which is of double type.
I want to decompose the values of data(1,:) to multiple variables something like below:
[frm_id,seq_id,xmin,ymin,w,h,temp1,temp2,temp3] = data(1,:);
In python it was straightforward, but above code gives following error in matlab:
Insufficient number of outputs from right hand side of equal sign to satisfy
assignment.
I can go with something like
frm_id = data(1,1);
seq_id = data(1,2);
%ect
But I do believe there must be matlab (more neat) way to do this operation.
Thanks!
You can use num2cell to convert the matrix to a cell array then copy contents of the cell to each variable:
C = num2cell(data,1);
[frm_id,seq_id,xmin,ymin,w,h,temp1,temp2,temp3] = C{:};
I can only suggest you to create a function like this:
function [frm_id,seq_id,xmin,ymin,w,h,temp1,temp2,temp3] = myfunction (data)
frm_id = data(:,1);
seq_id = data(:,2);
xmin = data(:,3);
ymin = data(:,4);
w = data(:,5);
h = data(:,6);
temp1 = data(:,7);
temp2 = data(:,8);
temp3 = data(:,9);
so in your main code
[frm_id,seq_id,xmin,ymin,w,h,temp1,temp2,temp3] = myfunction(data);

Matlab: initialize empty array of matrices

I need to create an empty array of matrices, and after fill it with matrices of the same size.
I have made a little script to explain:
result = [];
for i = 0: 4;
M = i * ones(5,5); % create matrice
result = [result,M]; % this would have to append M to results
end
Here result is a matrix of size 5*25 and I need an array of matrices 5*5*4.
I have been researched but I only found this line: result = [result(1),M];
The issue is that [] implicitly concatenates values horizontally (the second dimension). In your case, you want to concatenate them along the third dimension so you could use cat.
result = cat(3, result, M);
But a better way to do it would be to actually pre-allocate your result array using zeros
result = zeros(5, 5, 4);
And then within your loop fill each "slice" of the 3D array with the values.
for k = 0:4
M = k * ones(5,5);
result(:,:,k+1) = M;
end

Referencing Structs inside a Cell Array in Matlab

I'm dealing with a Matlab data structure which is analagous to "MyCellArray" in the following example:
% Create a Struct of string values inside a Cell Array
myCellArray = cell(3,1)
myStruct1 = struct('valA','aaa111','valB','bbb111','valC','ccc111')
myStruct2 = struct('valA','aaa222','valB','bbb222','valC','ccc222')
myStruct3 = struct('valA','aaa333','valB','bbb333','valC','ccc333')
myCellArray{1} = myStruct1
myCellArray{2} = myStruct2
myCellArray{3} = myStruct3
I'd like to be able to efficiently extract some of the data into a new array:
% Extract all valA values from myCellArray
% ArrayOfValA = myCellArray(< somehow get all the valA values >)
DesiredResult = cellstr(['aaa111';'aaa222';'aaa333']) % Or something similar
I'm new to Matlab and I just can't get my head around the notation. I've tried things like:
ArrayOfValA = myCellArray{(:,1).valA} % This is incorrect notation!
The real data is over 500K lines long so I'd like to avoid for loops or other iterative functions if possible. Unfortunately I can't change the original data structure but I suppose I could take a copy and manipulate that (I tried using struct2cell but I just got into another mess!). Is it possible to do this in a fast and efficient way?
Many thanks.
The following appears to work in Octave. I assume it also works in MATLAB:
>> temp = {[myCellArray{:}].valA}
temp =
{
[1,1] = aaa111
[1,2] = aaa222
[1,3] = aaa333
}
Does
myCellAsMat = cell2mat(myCellArray);
ArrayOfValA = vertcat(myCellAsMat(:).valA);
work?
edit: or horzcat, depending on the dimension and desired output of your valA field.

Resources