How to store output of an array?

The code works perfectly.
a=[0 200 900 1000 1200 1798 1799 1801 2000 2700 3601]
N = round(max(a)/900);
for k = 1:N
[~, ind(k)] = min(abs(a - 900*k));
end
For more arrays of a, i want to store the corresponding ind value. How can i do it?
example,
a=[0 200 900 1000 1200 1798 1799 1801 2000 2700 3601]
a=[0 1800 2000 2700 3600]
N = round(max(a)/900);
for k = 1:N
[~, ind(k)] = min(abs(a - 900*k));
end
For each array of a, how do i store the corresponding ind values?

Réponses (1)

Guillaume
Guillaume le 13 Juil 2015

0 votes

Here is a non-loopy version of your original code (I have no idea if it's faster than your code):
N = (1:round(max(a)/900))*900;
[~, ind] = min(abs(bsxfun(@minus, a', N)));
To do the same for several a arrays, first stores all these arrays into a cell array:
allAs = {
[0 200 900 1000 1200 1798 1799 1801 2000 2700 3601];
[0 1800 2000 2700 3600]
};
Then use a loop or cellfun to repeat the above or your code over the cell array:
[~, allInds] = cellfun(@(a) min(abs(bsxfun(@minus, a', (1:round(max(a)/900))*900))), ...
allAs, 'UniformOutput', false)

4 commentaires

yashvin
yashvin le 13 Juil 2015
Hi Guillaume,
Actually, It is an extension to this problem.
Any way of doing it without cellfun? I mean no use of an inbuilt matlab functions?
Stephen23
Stephen23 le 13 Juil 2015
Modifié(e) : Stephen23 le 13 Juil 2015
Without "inbuilt MATLAB functions" means that you cannot use min, :, or abs either.
Exactly what university lecturers and MATLAB beginners imagine when they say "no inbuilt functions" is sadly never clearly defined.
yashvin
yashvin le 13 Juil 2015
Ah sorry! My bad you are right. Being a beginner, I meant very common apporach, as I have no in depth knowledge of cellfun. I have a feeling that the solution is very simple. So any solution that is less complex than cellfun.
The problem is that ind which is the output of min cannot be specified in terms of cell . Else for each array, i could have stored it as a cell.
Sorry for the misinterpretation
cellfun is just a simple replacement for a loop that avoids you having to keep track of the numbers of elements and having to predeclare the result array. The equivalent code would be:
allInds = cell(size(allAs));
for iter = 1:numel(allAs)
a = allAs{iter};
[~, allInds{iter}] = min(abs(bsxfun(@minus, a', (1:round(max(a)/900))*900)));
end

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Question posée :

le 13 Juil 2015

Commenté :

le 13 Juil 2015

Community Treasure Hunt

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

Start Hunting!

Translated by