add two zeros on the left hand side of this vector,a=[1 2 3] in matlab

You can use the sprintf function to format the vector elements as strings with leading zeros, and then convert them back to numbers using str2num. Here's an example code:

main.m
a = [1 2 3];
a_str = sprintf('%02d ', a);
a_padded = str2num(a_str);
69 chars
4 lines

This code will create a new vector a_padded with the values [01 02 03]. The '%02d' format string in sprintf means that the number should be formatted with two digits and leading zeros if necessary. The ' ' character at the end of the format string adds a space between each formatted number. Finally, str2num converts the formatted string back to a numeric vector.

Alternatively, you could use the strjust function to left-justify the string representation of a and then concatenate '00 ' to each element:

main.m
a = [1 2 3];
a_str = strjust(num2str(a), 'left');
a_padded = str2num([repmat('00 ', size(a, 2), 1), a_str]);
109 chars
4 lines

This code uses num2str to convert a to a string, strjust to left-justify the string representation, and [repmat('00 ', size(a, 2), 1), a_str] to concatenate '00 ' to each element. Finally, str2num is used again to convert the padded string back to a numeric vector.

related categories

gistlibby LogSnag