how to create 2D matrix and calculate density of each element
2 次查看(过去 30 天)
显示 更早的评论
I'm new to matlab Can anyone help me out from this problem
- Accept the mass and the volume for 10 different objects labelled from 1 to 10 as 2D matrix.
- Calculate for each object the density using the equation: Density = mass/volume. Store the results in 1D array.
- Find the heaviest and the lightest objects (label and density) and print the results with an appropriate message.
- Generate a report showing the objects’ data (mass, volume, and density) sorted by the density.
0 个评论
回答(1 个)
Sayam Ganguly
2017-7-24
编辑:Sayam Ganguly
2017-7-24
Hi, I understand that you have 10 objects with Mass and Volume that you want to input to the program. Then you want to calculate the density of the objects and display the lightest and heaviest objects. Finally you want generate a report with sorted order of density. I'm assuming that the report would be an excel file. I would like to suggest an approach that should help you achieve this. Below is the code snippet with some instructions -
numInputs = 10;
mv = zeros(numInputs,3);
header = {'Desntiy' 'Label' 'Mass' 'Volume'};
for i = 1:numInputs
mv(i,1) = i;
%Take input from user.
mv(i,2) = input(['Enter Mass for object ' num2str(i) ' : ']);
end
%Use column slicer to access individual columns of the input array to calculate density
%Ex - mv(:,1) will give you the entire first column of the array mv
% Then generate the 1-d density matrix using'./' operator which performs an element wise division
of two arrays.
% Store the result of division in 1-d array called 'd'
[maxValue,maxLabel] = max(d);
% Similar to the line above also find the corresponding minimum value and index and store them in
%variables
fprintf('Heaviest is object %d with density %f\n',maxLabel,maxValue);
%Similarly show the lightest object
% Now horizontally concatenate 'd' and 'mv' to create the 'output' array
% Use horzcat(Refer to https://www.mathworks.com/help/matlab/ref/horzcat.html)
% for that
% Finally add header to 'Output' and generate excel using xlswrite(Refer https://www.mathworks.com/help/matlab/ref/xlswrite.html)
output = [header;num2cell(sortrows(output,1))];
Hope this helps!
2 个评论
Sayam Ganguly
2017-7-25
Yes you have to create the matrix 'd' by dividing the two columns of 'mv'. The entire code is not present in the answer. Follow the instructions in the comments and you should be able to complete the code.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!