Function - return array instead of single value
24 次查看(过去 30 天)
显示 更早的评论
Hey,
I have the following problem: The function stated below has an input of "lat_deg" and "long_deg" arrays. However, the output is currenty a single value. Why is that?
Thanks for your help!
function [foldername,filename,map_name,ref_name] = evaluatemapname(lat_deg,long_deg )
%Check if we need to add zeros in front of the expression, depending on
%the length of the number
if(abs(lat_deg) < 10)
map_lat = sprintf('0%d',abs(lat_deg));
else
map_lat = sprintf('%d',abs(lat_deg));
end
if(abs(long_deg) < 10)
map_long = sprintf('00%d',abs(long_deg));
elseif(abs(long_deg) < 100)
map_long = sprintf('0%d',abs(long_deg));
else
map_long = sprintf('%d',abs(long_deg));
end
%Norht, East
if(lat_deg >= 0 & long_deg >= 0)
foldername = sprintf('ASTGTM2_N%sE%s',map_lat,map_long);
filename = sprintf('ASTGTM2_N%sE%s_dem.tif',map_lat,map_long);
map_name = sprintf('Map_N%sE%s',map_lat,map_long);
ref_name = sprintf('R_N%sE%s',map_lat,map_long);
end
%Norht, West
if(lat_deg >= 0 & long_deg < 0)
foldername = sprintf('ASTGTM2_N%sW%s',map_lat,map_long);
filename = sprintf('ASTGTM2_N%sW%s_dem.tif',map_lat,map_long);
map_name = sprintf('Map_N%sW%s',map_lat,map_long);
ref_name = sprintf('R_N%sW%s',map_lat,map_long);
end
%South, West
if(lat_deg < 0 & long_deg < 0)
foldername = sprintf('ASTGTM2_S%sW%s',map_lat,map_long);
filename = sprintf('ASTGTM2_S%sW%s_dem.tif',map_lat,map_long);
map_name = sprintf('Map_S%sW%s',map_lat,map_long);
ref_name = sprintf('R_S%sW%s',map_lat,map_long);
end
%South, East
if(lat_deg < 0 & long_deg >= 0)
foldername = sprintf('ASTGTM2_S%sE%s',map_lat,map_long);
filename = sprintf('ASTGTM2_S%sE%s_dem.tif',map_lat,map_long);
map_name = sprintf('Map_S%sE%s',map_lat,map_long);
ref_name = sprintf('R_S%sE%s',map_lat,map_long);
end
end
2 个评论
Stephen23
2019-6-27
编辑:Stephen23
2019-7-5
"However, the output is currenty a single value. Why is that?"
If you expect to be able to supply arrays as the inputs then you will need to loop over their values (either explicitly or implictly) to create separate output strings (i.e. character vectors in a cell array, or string arrays). You could use a loop, or arrayfun, or compose, etc.
Note that you should read the sprintf documentation to understand what your code is doing now, and try some simple example with arrays, e.g.:
>> sprintf('%d,',1:4)
ans = 1,2,3,4,
Reading the documentation would also help you to simplify your code, e.g. replacing this
if(abs(long_deg) < 10)
map_long = sprintf('00%d',abs(long_deg));
elseif(abs(long_deg) < 100)
map_long = sprintf('0%d',abs(long_deg));
else
map_long = sprintf('%d',abs(long_deg));
end
with much simpler:
map_long = sprintf('%03d',abs(long_deg));
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!